package com.zy.cat.service.impl;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkMallUrlGenResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkGoodsDetailResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkGoodsSearchResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkLotteryUrlGenResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkResourceUrlGenResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkTopGoodsListQueryResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsOptGetResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkGoodsDetailResponse.GoodsDetailResponseGoodsDetailsItem;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkLotteryUrlGenResponse.LotteryUrlResponseUrlListItem;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkResourceUrlGenResponse.ResourceUrlResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkTopGoodsListQueryResponse.TopGoodsListGetResponseListItem;
import com.pdd.pop.sdk.http.api.pop.response.PddGoodsOptGetResponse.GoodsOptGetResponseGoodsOptListItem;
import com.taobao.api.internal.util.WebUtils;
import com.zy.cat.common.annotation.RedisPut;
import com.zy.cat.common.config.Configs;
import com.zy.cat.common.utils.CalculateUtil;
import com.zy.cat.common.utils.DateAPIUtils;
import com.zy.cat.common.utils.ExtendMethod;
import com.zy.cat.common.utils.HdkAPI;
import com.zy.cat.common.utils.JDAPI;
import com.zy.cat.common.utils.JISUAPI;
import com.zy.cat.common.utils.SpringContextUtil;
import com.zy.cat.common.utils.TBAPI;
import com.zy.cat.common.utils.TJKUtils;
import com.zy.cat.common.utils.ZTKAPI;
import com.zy.cat.common.utils.dtk.DTKAPI;
import com.zy.cat.dao.Dao;
import com.zy.cat.entity.ad.CatAppAd;
import com.zy.cat.entity.ad.CatAppAdOper;
import com.zy.cat.entity.ad.repository.CatAppAdRepository;
import com.zy.cat.entity.app.CatAppNewDeviceInfo;
import com.zy.cat.entity.app.CatAppPV;
import com.zy.cat.entity.app.CatAppVersion;
import com.zy.cat.entity.app.CatEventElement;
import com.zy.cat.entity.app.repository.CatAppNewDeviceInfoRepository;
import com.zy.cat.entity.app.repository.CatAppPvMenusRepository;
import com.zy.cat.entity.app.repository.CatEventElementRepository;
import com.zy.cat.entity.app.resp.CatAppGoodsMsgResp;
import com.zy.cat.entity.app.CatAppUseVideo;
import com.zy.cat.entity.app.resp.CatAppVersionInfoResp;
import com.zy.cat.entity.app.resp.NewItemResp;
import com.zy.cat.entity.dev.CatDevRegisterInfo;
import com.zy.cat.entity.dev.CatDevRelation;
import com.zy.cat.entity.dev.CatDevSignedBeansHistory;
import com.zy.cat.entity.dev.CatDevSignedHistory;
import com.zy.cat.entity.dev.CatDevUserInfo;
import com.zy.cat.entity.dev.CatDevWeInfo;
import com.zy.cat.entity.dev.act.resp.APPActDBHistoryResp;
import com.zy.cat.entity.dev.act.resp.CatDailyDrawDetailResp;
import com.zy.cat.entity.dev.act.resp.CatDailyDrawListResp;
import com.zy.cat.entity.dev.act.resp.CatDailyDrawListResp.Prize;
import com.zy.cat.entity.dev.garden.CatUserTreeTask;
import com.zy.cat.entity.dev.garden.resp.CatTreeDetailResp;
import com.zy.cat.entity.dev.garden.resp.CatUserTreeResp;
import com.zy.cat.entity.dev.repository.CatDevNewAddOrderHistoryRepository;
import com.zy.cat.entity.dev.repository.CatDevRegisterInfoRepository;
import com.zy.cat.entity.dev.repository.CatDevRelationRepository;
import com.zy.cat.entity.dev.repository.CatDevRemitInfoRepository;
import com.zy.cat.entity.dev.repository.CatDevUserInfoRepository;
import com.zy.cat.entity.dev.resp.CatDev5088InviteInfoResp.InviteRemit;
import com.zy.cat.entity.dev.resp.CatDev5088InviteInfoResp;
import com.zy.cat.entity.dev.resp.CatDevBeanVideoHistoryResp;
import com.zy.cat.entity.dev.resp.CatDevFertilizerVideoHistoryResp;
import com.zy.cat.entity.dev.resp.CatDevOrderResp;
import com.zy.cat.entity.dev.resp.CatDevRemitRecordResp;
import com.zy.cat.entity.dev.resp.CatDevSignedHistoryResp;
import com.zy.cat.entity.dev.resp.CatDevUserInfoResp;
import com.zy.cat.entity.dev.resp.CatDevUserInfoResp.CashBalanceInfo;
import com.zy.cat.entity.dev.resp.CatDevZJInviteInfoResp;
import com.zy.cat.entity.dtk.Goods;
import com.zy.cat.entity.dtk.GoodsDetail;
import com.zy.cat.entity.dtk.GoodsDetail.Detail;
import com.zy.cat.entity.dtk.GoodsRank;
import com.zy.cat.entity.dtk.GoodsTopic.Opts;
import com.zy.cat.entity.dtk.SuperCategory;
import com.zy.cat.entity.dtk.SuperCategory.Category;
import com.zy.cat.entity.dtk.resp.GoodsActivityListResp;
import com.zy.cat.entity.dtk.resp.GoodsActivityListResp.Data;
import com.zy.cat.entity.dtk.resp.GoodsActivityResp;
import com.zy.cat.entity.dtk.resp.GoodsActivityResp.Activitys;
import com.zy.cat.entity.dtk.resp.GoodsListResp;
import com.zy.cat.entity.dtk.resp.GoodsNineResp;
import com.zy.cat.entity.dtk.resp.GoodsRankListResp;
import com.zy.cat.entity.dtk.resp.GoodsTopicListResp;
import com.zy.cat.entity.game.CVSDrawHistory;
import com.zy.cat.entity.game.CardDrawBannerConf;
import com.zy.cat.entity.game.CardDrawCountHistory;
import com.zy.cat.entity.game.CardDrawEntryInfo;
import com.zy.cat.entity.game.CardNewHistory;
import com.zy.cat.entity.game.CardPokerDrawCountHistory;
import com.zy.cat.entity.game.CatScrollBarInfo;
import com.zy.cat.entity.game.repository.CardDrawBannerConfRepository;
import com.zy.cat.entity.game.repository.CardDrawCountHistoryRepository;
import com.zy.cat.entity.game.repository.CardNewHistoryRepository;
import com.zy.cat.entity.game.repository.CardPokerDrawCountHistoryRepository;
import com.zy.cat.entity.game.repository.CatDevSignedBeansHistoryRepository;
import com.zy.cat.entity.game.repository.CatScrollBarInfoRepository;
import com.zy.cat.entity.game.resp.CardDrawBannerResp;
import com.zy.cat.entity.game.resp.CardDrawCountHistoryResp;
import com.zy.cat.entity.game.resp.FruitPrinceInfoResp;
import com.zy.cat.entity.game.resp.ScrollBarInfoResp;
import com.zy.cat.entity.hdk.HdkGoodsItem;
import com.zy.cat.entity.hdk.HdkSuperCategory;
import com.zy.cat.entity.jd.JDGoods;
import com.zy.cat.entity.mall.CatGoodsCategoryInfo;
import com.zy.cat.entity.mall.CatGoodsFavoritesInfo;
import com.zy.cat.entity.mall.repository.CatGoodsCategoryRepository;
import com.zy.cat.entity.mall.repository.CatGoodsSubsidyHistoryRepository;
import com.zy.cat.entity.mall.resp.CatBansResp;
import com.zy.cat.entity.mall.resp.CatDouYinVideoResp;
import com.zy.cat.entity.mall.resp.CatGoodsCategoryResp;
import com.zy.cat.entity.mall.resp.CatTalentInfoResp;
import com.zy.cat.entity.mall.resp.FlashSaleGoodsResp;
import com.zy.cat.entity.mall.resp.FlashSaleGoodsResp.FlashSaleGoods;
import com.zy.cat.entity.mall.resp.TKSelectionResp;
import com.zy.cat.entity.mall.resp.TKTLJGoodsResp;
import com.zy.cat.entity.mall.resp.TkDetailPicsResp;
import com.zy.cat.entity.mall.resp.ZTKShopResp;
import com.zy.cat.entity.resp.Pages;
import com.zy.cat.entity.resp.ResultPage;
import com.zy.cat.entity.tb.resp.TKMaterialResp;
import com.zy.cat.entity.tb.resp.TKTQGResp;
import com.zy.cat.entity.wx.WxSessionInfo;
import com.zy.cat.entity.ztk.resp.ZTKShopDetail;
import com.zy.cat.service.AsyncService;
import com.zy.cat.service.CacheService;

import jd.union.open.category.goods.get.response.UnionOpenCategoryGoodsGetResponse;
import jd.union.open.goods.bigfield.query.response.UnionOpenGoodsBigfieldQueryResponse;
import jd.union.open.goods.jingfen.query.response.UnionOpenGoodsJingfenQueryResponse;
import jd.union.open.goods.promotiongoodsinfo.query.response.UnionOpenGoodsPromotiongoodsinfoQueryResponse;
import jd.union.open.goods.query.response.UnionOpenGoodsQueryResponse;

import com.zy.cat.common.utils.PDDAPI;
import com.zy.cat.entity.pdd.PddMallConvert;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @info
 * @author Link
 * @date 2019-11-28 14:04
 */
@Service
@Slf4j
public class CacheServiceImpl implements CacheService {

	@Autowired
	Dao<APPActDBHistoryResp> ccdao;

	/* 广告点击率正常比Key */
	private final String AD_STANDARD_CLICK_RATE_KEY = "AD_STANDARD_CLICK_RATE";

	@Autowired
	Configs configs;

	@Autowired
	Dao<CVSDrawHistory> cddao;

	@Autowired
	@Qualifier("redis10")
	RedisTemplate<String, Object> redis10;

	@Autowired
	@Qualifier("redis1")
	RedisTemplate<String, String> redis1;

	@Autowired
	@Qualifier("redis9")
	RedisTemplate<String, String> redis9;

	@Autowired
	@Qualifier("redis11")
	RedisTemplate<String, Object> redis11;

	@Autowired
	@Qualifier("redis14")
	RedisTemplate<String, String> redis14;

	@Autowired
	Dao<TKTLJGoodsResp> gdao;

	@Autowired
	CatDevUserInfoRepository catDevUserInfoRepository;

	@Autowired
	CardNewHistoryRepository cardNewHistoryRepository;

	@Autowired
	CatScrollBarInfoRepository catScrollBarInfoRepository;
	
	@Autowired
	CatEventElementRepository catEventElementRepository;
	
	@Autowired
	CatDevRemitInfoRepository catDevRemitInfoRepository;

	@Autowired
	CatDevNewAddOrderHistoryRepository newAddOrderHistoryRepository;

	@Autowired
	CatDevRelationRepository catDevRelationRepository;

	@Autowired
	Dao<CatDevUserInfoResp> catDao;
	
	@Autowired
	Dao<CatUserTreeResp> catUserDao;
	
	@Autowired
	Dao<CashBalanceInfo> cashBalanceInfoDao;
	@Autowired
	Dao<CatBansResp> banDao;

	@Autowired
	Dao<Long> longDao;

	@Autowired
	Dao<Integer> intDao;

	@Autowired
	Dao<TKSelectionResp> selectionDao;

	@Autowired
	Dao<GoodsRankListResp> goodsRankDao;

	@Autowired
	Dao<GoodsListResp> glDao;

	@Autowired
	Dao<CatDevRemitRecordResp> remitDao;

	@Autowired
	Dao<CardDrawEntryInfo> cardDrawEntryInfoDao;

	@Autowired
	Dao<FruitPrinceInfoResp> fpdao;

	@Autowired
	Dao<CardDrawBannerResp> cardDrawBannerRespDao;

	@Autowired
	Dao<CatDevBeanVideoHistoryResp> beanVideoHistoryRespDao;
	
	@Autowired
	Dao<CatDevFertilizerVideoHistoryResp> fertilizerVideoHistoryRespDao;

	@Autowired
	Dao<CatAppVersionInfoResp> catAppVersionInfoRespDao;

	@Autowired
	Dao<CatGoodsFavoritesInfo> catGoodsFavoritesInfoDao;

	@Autowired
	Dao<CatAppAdOper> catAppAdOperDao;

	@Autowired
	Dao<CatDevSignedHistoryResp> signedHistoryRespDao;

	@Autowired
	CardPokerDrawCountHistoryRepository cardPokerDrawCountHistoryRepository;

	@Autowired
	CardDrawCountHistoryRepository cardDrawCountHistoryRepository;

	@Autowired
	CatAppNewDeviceInfoRepository catAppNewDeviceInfoRepository;

	@Autowired
	CatDevRegisterInfoRepository catDevRegisterInfoRepository;

	@Autowired
	CatAppPvMenusRepository catAppPvMenusRepository;

	@Autowired
	CardDrawBannerConfRepository cardDrawBannerConfRepository;

	@Autowired
	CatGoodsSubsidyHistoryRepository goodsSubsidyHistoryRepository;

	@Autowired
	CatGoodsCategoryRepository catGoodsCategoryRepository;

	@Autowired
	CatDevSignedBeansHistoryRepository signedBeansHistoryRepository;

	@Autowired
	CatAppAdRepository catAppAdRepository;

	@Autowired
	Dao<InviteRemit> rdao;

	@Autowired
	AsyncService asyncService;

	@Autowired
	@Qualifier("redis2")
	RedisTemplate<String, Object> redis2;

	@Autowired
	Dao<com.zy.cat.entity.dev.act.resp.APPActDBInfoResp.Goods> cgdao;
	
	@Autowired
	Dao<CatDailyDrawListResp.Prize> dailyDrawDao;
	
	@Autowired
	Dao<CatDailyDrawDetailResp> dailyDrawDetailRespDao;
	
	@Autowired
	Dao<CatTreeDetailResp> treeDetailRespDao;
	
	@Override
	@RedisPut(db = 10, rtype = 2, key = "CAT_JD_GOODS_JX", hashKey = "+#key", timeOut = 1, timeUnit = TimeUnit.HOURS)
	public UnionOpenGoodsJingfenQueryResponse getJdJXGoods(String key, int eid, int stype, String sort, Pages pages) {
		//排序字段(price：单价, commissionShare：佣金比例, commission：佣金， inOrderCount30DaysSku：sku维度30天引单量，comments：评论数，goodComments：好评数)
		String sortName="comments";
		if(stype==0) {
			sortName="price";
		}else if(stype==1) {
			sortName="commissionShare";
		}else if(stype==2) {
			sortName="commission";
		}else if(stype==3) {
			sortName="inOrderCount30DaysSku";
		}else if(stype==4) {
			sortName="comments";
		}else if(stype==5) {
			sortName="goodComments";
		}
		UnionOpenGoodsJingfenQueryResponse result=JDAPI.getInstance(0).getJingFen(eid, pages.getPageNum(), pages.getPageSize(), sortName, sort);
		if(result!=null&&result.getData()!=null&&result.getData().length>0) {
			 return result;
		 }
		return null;
	}

	
	@Override
	@RedisPut(db = 10, rtype = 2, key = "CAT_JD_GOODS_CATS", hashKey = "+#parent+_+#grade", timeOut = 1, timeUnit = TimeUnit.HOURS)
	public UnionOpenCategoryGoodsGetResponse getJdGoodsCat(int parent, int grade) {
		 UnionOpenCategoryGoodsGetResponse result=JDAPI.getInstance(0).getCats(parent, grade);
		 if(result!=null&&result.getData()!=null&&result.getData().length>0) {
			 return result;
		 }
		return null;
	}
	
	@Override
	@RedisPut(db = 10, rtype = 2, key = "CAT_JD_GOODS_LIKE", hashKey = "+#key", timeOut = 1, timeUnit = TimeUnit.HOURS)
	public UnionOpenGoodsQueryResponse getJdGoodsLike(String key,int ctype, Long cid1, Long cid2, Long cid3) {
		UnionOpenGoodsQueryResponse result=JDAPI.getInstance(ctype).getGoodsLike(cid1,cid2,cid3);
		if(result!=null&&result.getData()!=null&&result.getData().length>0) {
			return result;
		}
		return null;
	}

	@Override
	@RedisPut(db = 10, rtype = 2, key = "CAT_JD_GOODS_LIST", hashKey = "+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public UnionOpenGoodsQueryResponse getJdCatGoods(int ctype,String key,int pageIndex, Long cid1, Long cid2, Long cid3,int stype, String sort, int isCoupon) {
		//排序字段(price：单价, commissionShare：佣金比例, commission：佣金， inOrderCount30Days：30天引单量， inOrderComm30Days：30天支出佣金)
				String sortName="price";
				if(stype==0) {
					sortName="price";
				}else if(stype==1) {
					sortName="commissionShare";
				}else if(stype==2) {
					sortName="commission";
				}else if(stype==3) {
					sortName="inOrderCount30Days";
				}else if(stype==4) {
					sortName="inOrderComm30Days";
				} 
		UnionOpenGoodsQueryResponse result=JDAPI.getInstance(ctype).getGoods(pageIndex, "", cid1, cid2, cid3,sortName,sort, isCoupon,"");
		if(result!=null&&result.getData()!=null&&result.getData().length>0) {
			return result;
		}
		return null;
	}

	@Override
	@RedisPut(db = 10, rtype = 2, key = "CAT_JD_GOODS_SEARCH", hashKey = "+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public UnionOpenGoodsQueryResponse getJdGoodsSearch(int ctype,String key, int pageIndex, String keyWords, String sort, int stype, int isCoupon,String owner) {
		//排序字段(price：单价, commissionShare：佣金比例, commission：佣金， inOrderCount30Days：30天引单量， inOrderComm30Days：30天支出佣金)
		String sortName="price";
		if(stype==0) {
			sortName="price";
		}else if(stype==1) {
			sortName="commissionShare";
		}else if(stype==2) {
			sortName="commission";
		}else if(stype==3) {
			sortName="inOrderCount30Days";
		}else if(stype==4) {
			sortName="inOrderComm30Days";
		} 
		UnionOpenGoodsQueryResponse result=JDAPI.getInstance(ctype).getGoods(pageIndex, keyWords, null, null, null,sortName,sort,isCoupon,owner);
		if(result!=null&&result.getData()!=null&&result.getData().length>0) {
			return result;
		}
		return null;
	}

	@Override
	@RedisPut(db = 10, rtype = 2, key = "CAT_JD_GOODS_INFO", hashKey = "+#skuid", timeOut = 1, timeUnit = TimeUnit.HOURS)
	public UnionOpenGoodsPromotiongoodsinfoQueryResponse getJdGoodsInfo(int ctype,String skuid) {
		UnionOpenGoodsPromotiongoodsinfoQueryResponse result = JDAPI.getInstance(ctype).getGoodsInfo(skuid);
		if(result!=null&&result.getData()!=null&&result.getData().length>0) {
			return result;
		}
		return null;
	}

	@Override
	@RedisPut(db = 10, rtype = 2, key = "CAT_PDD_SHOP_OPTS_INFO", hashKey = "+#optid", timeOut = 10, timeUnit = TimeUnit.DAYS)
	public List<Map<String, Object>> getPddOpts(int optid) {
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> result2 = new ArrayList<Map<String, Object>>();

		if (optid == 0) {
			List<String> optIds = new ArrayList<String>();
			optIds.add("1");
			optIds.add("4");
			optIds.add("13");
			optIds.add("15");
			optIds.add("2946");
			optIds.add("14");
			optIds.add("16");
			optIds.add("18");
			optIds.add("743");
			optIds.add("818");
			optIds.add("1281");
			optIds.add("1282");
			optIds.add("1451");
			optIds.add("10301");
			optIds.add("3162");

			Map<String, GoodsOptGetResponseGoodsOptListItem> opts = new HashMap<String, GoodsOptGetResponseGoodsOptListItem>();
			PDDAPI.getInstance(1,0).getShopOpts(0).getGoodsOptGetResponse().getGoodsOptList().forEach(opt -> {
				opts.put(opt.getOptId() + "", opt);
			});

			optIds.forEach(action -> {
				GoodsOptGetResponseGoodsOptListItem ropt = opts.get(action);
				Map<String, Object> rfopts = new HashMap<>();
				rfopts.put("level", ropt.getLevel());
				rfopts.put("opt_name", ropt.getOptName());
				rfopts.put("opt_id", ropt.getOptId());
				rfopts.put("child", PDDAPI.getInstance(1,0).getShopOpts(ropt.getOptId().intValue())
						.getGoodsOptGetResponse().getGoodsOptList());
				result.add(rfopts);
			});
		} else {
			PddGoodsOptGetResponse resp = PDDAPI.getInstance(1,0).getShopOpts(optid);
			if (resp != null && resp.getGoodsOptGetResponse() != null
					&& resp.getGoodsOptGetResponse().getGoodsOptList() != null) {
				resp.getGoodsOptGetResponse().getGoodsOptList().forEach(ropt -> {
					Map<String, Object> rfopts = new HashMap<>();
					rfopts.put("level", ropt.getLevel());
					rfopts.put("opt_name", ropt.getOptName());
					rfopts.put("opt_id", ropt.getOptId());
					rfopts.put("parent_opt_id", ropt.getParentOptId());
					result2.add(rfopts);
				});
			}
			result.addAll(result2);
		}
		return result;
	}

	@Override
	@RedisPut(db = 10, rtype = 2, key = "CAT_PDD_SHOPS_DETAILS_INFO", hashKey = "+#sid", timeOut = 1, timeUnit = TimeUnit.HOURS)
	public String getPddShopInfo(long sid) {
		String result = null;
		PddDdkGoodsDetailResponse resp = PDDAPI.getInstance(1,0).getshopsInfo(sid);
		if (resp != null && resp.getGoodsDetailResponse() != null) {
			List<GoodsDetailResponseGoodsDetailsItem> shops = resp.getGoodsDetailResponse().getGoodsDetails();
			if (shops != null && !shops.isEmpty()) {
				result = JSON.toJSONString(shops.get(0));
			}
		}
		return result;
	}

	@Override
	@RedisPut(db = 13, key = "CAT_PDD_TOP_SHOPS_INFO_+#stype+_+#page", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public String getPddTopShipList(String pid,int page, int stype) {
		PddDdkTopGoodsListQueryResponse response = PDDAPI.getInstance(1,0).getTopShops(pid,stype, page);
		if (response == null || response.getTopGoodsListGetResponse() == null
				|| response.getTopGoodsListGetResponse().getList() == null
				|| response.getTopGoodsListGetResponse().getList().isEmpty()) {
			return null;
		}
		List<TopGoodsListGetResponseListItem> resultPojo = response.getTopGoodsListGetResponse().getList();
		return JSON.toJSONString(resultPojo);
	}

	@Override
	@RedisPut(db = 13, key = "CAT_PDD_SHOP_LIST_+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public PddDdkGoodsSearchResponse getPddShopList(String pid,String key, String query, int pageNum, int pageSize, int sortType,
			long cat_id, long opt_id, boolean withCoupon) {
		PddDdkGoodsSearchResponse shopList = PDDAPI.getInstance(1,1).getshops(pid,query, pageNum, pageSize, sortType, cat_id,
				opt_id, withCoupon);
		return shopList;
	}

	@Override
	@RedisPut(db = 13, key = "CAT_PDD_LOTTERY_URL_+#upid", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public String getPddLotteryUrl(String upid) {
		PddDdkLotteryUrlGenResponse response = PDDAPI.getInstance(1,0).getLotteryUrl(upid);
		if (response == null || response.getLotteryUrlResponse() == null
				|| response.getLotteryUrlResponse().getUrlList() == null
				|| response.getLotteryUrlResponse().getUrlList().isEmpty()) {
			return null;
		}
		List<LotteryUrlResponseUrlListItem> resultPojo = response.getLotteryUrlResponse().getUrlList();
		return JSON.toJSONString(resultPojo);
	}

	@Override
	@RedisPut(db = 13, key = "CAT_PDD_RESOURCE_URL_+#upid+_+#rtype", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public String getPddResourceUrl(String upid, int rtype) {
		PddDdkResourceUrlGenResponse response = PDDAPI.getInstance(1,0).getResourceUrl(upid, rtype);
		if (response == null || response.getResourceUrlResponse() == null) {
			return null;
		}
		ResourceUrlResponse resultPojo = response.getResourceUrlResponse();
		return JSON.toJSONString(resultPojo);
	}

	@Override
	@RedisPut(db = 13, key = "CAT_PDD_MALL_CONVERT_+#ctype+_+#rtype+_+#upid+_+#mid", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public PddMallConvert getPddMallConvert(int ctype,int rtype, String upid, long mid) {
		PddMallConvert result = null;
		PddDdkMallUrlGenResponse response = PDDAPI.getInstance(1,ctype).getMallConvert(upid, mid);
		if (response != null && response.getMallCouponGenerateUrlResponse() != null
				&& response.getMallCouponGenerateUrlResponse().getList() != null) {
			String responseJson = JSON.toJSONString(response.getMallCouponGenerateUrlResponse().getList().get(0));
			result = JSON.parseObject(responseJson, PddMallConvert.class);
		}
		return result;
	}

	@Override
	@RedisPut(db = 7, rtype = 2, key = "CAT_CJ_GOODS_LIST", hashKey = "+#pid", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public List<com.zy.cat.entity.dev.act.resp.APPActDBInfoResp.Goods> getDbGoods(String pid) {
		return cgdao.list(new APPActDBHistoryResp(pid), "getGoodsInfo");
	}

	@Override
	@RedisPut(db = 7, rtype = 2, key = "CAT_CJ_GOODS_MAX_QID", hashKey = "+#sid+_+#cindex", timeOut = 1, timeUnit = TimeUnit.HOURS)
	public long getMaxQid(String sid, int cindex) {
		long qid = 10000000;
		APPActDBHistoryResp getMaxQid = ccdao.selectOne(new APPActDBHistoryResp(sid, cindex), "getMaxQid");
		if (getMaxQid != null) {
			qid = getMaxQid.getQid();
		}
		return qid;
	}

	@Override
	@RedisPut(db = 7, rtype = 2, key = "CAT_CJ_GOODS_MAX_CINDEX", hashKey = "+#sid", timeOut = 1, timeUnit = TimeUnit.HOURS)
	public int getMaxCindex(String sid) {
		int cindex = 1;
		APPActDBHistoryResp getMaxCindex = ccdao.selectOne(new APPActDBHistoryResp(sid, 1), "getMaxCindex");
		if (getMaxCindex != null) {
			cindex = getMaxCindex.getCindex();
		}
		return cindex;

	}
//	@Override
//	public String getCatWeAppUnionidByCode(String code) {
//		String url = "https://api.weixin.qq.com/sns/jscode2session";
//		Map<String, String> params = new HashMap<String, String>();
//		params.put("appid", "wx0c0aecf0cb2b2830");
//		params.put("secret", "dd8081a7526c036a9368c06858b8a1ff");
//		params.put("js_code", code);
//		params.put("grant_type", "authorization_code");
//		String resultJson = null;
//		String result = null;
//		try {
//			resultJson = WebUtils.doGet(url, params);
//			log.info("-getWeAppUnionidByCode-->" + resultJson);
//		} catch (IOException e) {
//			return null;
//		}
//		if (resultJson != null && JSONObject.isValid(resultJson)) {
//			JSONObject jo = JSONObject.parseObject(resultJson);
//			if (jo != null) {
//				if (jo.containsKey("errcode")) {
//					return null;
//				} else {
//					result = jo.getString("unionid");
//				}
//
//			}
//		}
//		return result;
//	}

	@Override
	@RedisPut(db = 2, key = "WECHAT_ACCESS_TOKEN_+#appid", timeOut = 7000, timeUnit = TimeUnit.SECONDS)
//	redis2.opsForHash().putAll("WECHAT_LAST_ACCESS_TOKEN_"+appid, map);
	public String getWechatAccessToken(String appid, String secret) {
		String resultJson = "";
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret="
				+ secret;
		try {
			resultJson = WebUtils.doGet(url, null, "UTF-8");
		} catch (IOException e) {
			log.error("-getWechatAccessToken-->" + resultJson);
			log.error(e.getLocalizedMessage());
		}
		if (JSONObject.isValidObject(resultJson) && resultJson.contains("access_token")) {
			JSONObject rjob = JSONObject.parseObject(resultJson);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("info", "记录微信公众号AccessToken最后获取的信息");
			map.put("time", com.taobao.api.internal.util.StringUtils.formatDateTime(new Date()));
			map.put("access_token", rjob.getString("access_token"));
			map.put("expires_in", rjob.getIntValue("expires_in"));
			/* 记录WECHAT_ACCESS_TOKEN 最后获取的时间等信息 */
			redis2.opsForHash().putAll("WECHAT_LAST_ACCESS_TOKEN_" + appid, map);
			return rjob.getString("access_token");
		} else {
			log.error("-getWechatAccessToken-->" + resultJson);
		}
		return null;
	}

	@Override
	public String[] getWeAppUnionidByCode(String code) {
		String[] results = { code, code };
		if (SpringContextUtil.isDev()) {
			log.info("-开发环境，微信无需获取unionid,直接返回CODE-{}", code);
			return results;
		}

		String url = "https://api.weixin.qq.com/sns/jscode2session";
		Map<String, String> params = new HashMap<String, String>();
		params.put("appid", "wx0c0aecf0cb2b2830");
		params.put("secret", "dd8081a7526c036a9368c06858b8a1ff");
		params.put("js_code", code);
		params.put("grant_type", "authorization_code");
		String resultJson = null;
		try {
			resultJson = WebUtils.doGet(url, params);
			log.info("-getWeAppUnionidByCode-->" + resultJson);
		} catch (IOException e) {
			return null;
		}
		if (resultJson != null && JSONObject.isValid(resultJson)) {
			JSONObject jo = JSONObject.parseObject(resultJson);
			if (jo != null) {
				if (jo.containsKey("errcode")) {
					return null;
				} else {
					results[0] = jo.getString("unionid");
					results[1] = jo.getString("openid");
				}
			}
		}
		return results;
	}

	@Override
	@RedisPut(rtype = 2, db = 13, key = "CAT_DEV_INFO", hashKey = "+#unionid", timeOut = 1, timeUnit = TimeUnit.DAYS)
	public String getCatDevUserInfoByUnionid(String unionid) {
		// 查询此unionid的账号状态为未注销的账号
//		return catDevUserInfoRepository.findByUnionidAndIstatusNot(unionid,2);

		CatDevUserInfo cacheEntity = catDevUserInfoRepository.findByUnionidAndIstatusNot(unionid, 2);
		if (cacheEntity == null) {
			return null;
		}
		return JSON.toJSONString(cacheEntity);
	}

	@Override
	@RedisPut(rtype = 2, db = 13, key = "CAT_DEV_INFO", hashKey = "+#phone", timeOut = 1, timeUnit = TimeUnit.DAYS)
	public String getCatDevUserInfoByPhone(String phone) {
		List<CatDevUserInfo> list = catDevUserInfoRepository.findByPhone(phone);
		if (list == null || list.size() == 0) {
			return null;
		}
		// 对数据进行筛选
		CatDevUserInfo cacheEntity = null;
		for (CatDevUserInfo info : list) {
			if (info.getIstatus() != 2) {
				cacheEntity = info;
				break;
			}
		}
		// 全为已注销用户，则直接范围任意一个实例
		if (cacheEntity == null) {
			cacheEntity = list.get(0);
		}
		return JSON.toJSONString(cacheEntity);
	}

	@Override
	@RedisPut(rtype = 2, db = 13, key = "CAT_DEV_INFO", hashKey = "+#pid", timeOut = 1, timeUnit = TimeUnit.DAYS)
	public String getCatDevUserInfoByPid(String pid) {
//		CatDevUserInfo userInfo = catDevUserInfoRepository.findByPid(pid);
//		return userInfo;
		CatDevUserInfo cacheEntity = catDevUserInfoRepository.findByPid(pid);
		if (cacheEntity == null) {
			return null;
		}
		return JSON.toJSONString(cacheEntity);
	}

	@Override
	public CatDevUserInfoResp getCatDevUserLoginInfo(String unionid) {
		CatDevUserInfoResp userInfoResp = catDao.selectOne(new CatDevUserInfo(unionid, unionid), "loginInfo");
		return userInfoResp;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_BANNERS_+#sex", timeOut = 6000, timeUnit = TimeUnit.SECONDS)
	public List<CatBansResp> getBanners(Integer sex) {
		return banDao.list(new CatBansResp(sex), "getBanners");
	}

	@Override
	@RedisPut(db = 11, key = "CAT_TODAY_TJ_+#rtype+_+#sex+_+#pages.pageNum+_+#pages.pageSize", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public ResultPage<TKSelectionResp> getTodayTJList(int rtype, int sex, Pages pages) {
		//从数据库中获取所有选品库配置信息
		List<Map<String, String>> favoritesList = getFavoritesList(0);
		Map<String, String> map = new HashMap<>();
		favoritesList.forEach(obj -> {
			map.put(obj.get("cname"), obj.get("cid"));
		});
		long favoritesId = Long.parseLong(map.get("通用库"));
		TBAPI tbapi = TBAPI.getInstance(TBAPI.DEFAULT_TYPE);
		//调用淘宝API查询商品
		ResultPage<TKSelectionResp> resultPage = tbapi.getTbkUatmFavoritesItem(favoritesId, pages);
		// 商品过滤设置
		return filterGoodsPlus(resultPage);
	}

	/**
	 * 将已失效的商品过滤掉
	 * 
	 * @author lipengchao
	 * @date 2019-12-10 10:34:55
	 * @param resultPage
	 * @return
	 */
	private ResultPage<TKSelectionResp> filterGoods(ResultPage<TKSelectionResp> resultPage) {
		if (resultPage == null && resultPage.getList()!=null) {
			return null;
		}
		if (resultPage.getList() != null && resultPage.getList().size() > 0) {
			List<TKSelectionResp> list = resultPage.getList().stream().filter(resp -> resp.getStatus() == 1)
					.collect(Collectors.toList());
			resultPage.setList(list);
		}
		return resultPage;
	}

	/**
	 * 将已失效的商品过滤掉和无优惠券的商品
	 * 
	 * @author lipengchao
	 * @date 2019-12-10 10:34:55
	 * @param resultPage
	 * @return
	 */
	private ResultPage<TKSelectionResp> filterGoodsPlus(ResultPage<TKSelectionResp> resultPage) {
		if (resultPage == null) {
			return null;
		}
		if (resultPage.getList() != null && resultPage.getList().size() > 0) {
			List<TKSelectionResp> list = resultPage.getList().stream()
					.filter(resp -> resp.getStatus() == 1 && resp.getCouponRemainCount() != null
							&& resp.getCouponRemainCount() > 0 && !(resp.getCouponEndTime() != null
							&& !TJKUtils.parse2LocalDate(resp.getCouponEndTime()).plusDays(1).isAfter(LocalDate.now())))
					.collect(Collectors.toList());
			resultPage.setList(list);
		}
		return resultPage;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_WL_+#key", timeOut = 6000, timeUnit = TimeUnit.SECONDS)
	public ResultPage<TKMaterialResp> getWLList(String key, Long materialId, String imei, Pages pages) {
		TBAPI tbapi = TBAPI.getInstance(TBAPI.DEFAULT_TYPE);
		// 调用查询物料api
		return tbapi.getTbkDgOptimusMaterial((long) materialId, imei,"", pages);
	}

	@Override
	@RedisPut(db = 11, key = "CAT_DDQ_+#key", timeOut = 6000, timeUnit = TimeUnit.SECONDS)
	public List<TKTQGResp> getTQGList(String key, String stime, Pages pages) {
		TBAPI tbapi = TBAPI.getInstance(TBAPI.DEFAULT_TYPE);
		// 调用查询淘抢购API
		return tbapi.getTbkJuTqg(stime, pages.getPageNum(), pages.getPageSize());
	}

	@Override
	@RedisPut(db = 11, key = "CAT_GOODS_DETAIL_+#sid", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public GoodsDetail getGoodsDetail(String sid) {
		DTKAPI api = DTKAPI.getInstance(0);
		// 调用大淘客API查询商品详情
		GoodsDetail shopDetail = api.getShopDetail(sid, sid);
		Detail data = shopDetail.getData();
		if (shopDetail.getData() != null) {
			shopDetail.getData()
					.setFcode(CalculateUtil.getRebateAmount(data.getActualPrice(), data.getCommissionRate()));
			
			//对商品详情图处理
			if (!StringUtils.isEmpty(shopDetail.getData().getDetailPics())) {
				List<TkDetailPicsResp> list = JSON.parseArray(shopDetail.getData().getDetailPics(),TkDetailPicsResp.class);
				StringBuffer buffer=new StringBuffer();
				List<String> collect = list.stream().map(obj->{
					return obj.getImg();
				}).collect(Collectors.toList());
				shopDetail.getData().setDetailPics(StringUtils.join(collect.toArray(),","));
			}
			//获取淘宝详情数据
			String tbkItemInfo = TBAPI.getInstance(10).getTbkItemInfo(sid);
			if (!StringUtils.isEmpty(tbkItemInfo)) {
				JSONObject jsonObject = JSON.parseObject(tbkItemInfo);
				shopDetail.getData().setProvcity(jsonObject.getString("provcity"));
				shopDetail.getData().setFreeShipment(jsonObject.getBoolean("free_shipment"));
				shopDetail.getData().setReservePrice(jsonObject.getString("reserve_price"));
				shopDetail.getData().setOriginalPrice(jsonObject.getDouble("zk_final_price"));
			}
			return shopDetail;
		} else {
			// 商品不存在,说明商品已下架,删除数据库中商品信息
			glDao.delete(new GoodsListResp(sid), "deleteBySid");
		}
		return null;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_DTK_9.9_GOODS_+#key", timeOut = 1, timeUnit = TimeUnit.HOURS)
	public GoodsNineResp getGoodsNine(String key, int nineCid, String pageId, int pageSize) {
		DTKAPI api = DTKAPI.getInstance(0);
		// 调用大淘客API查询9.9包邮精选
		Goods goodsNine = api.getGoodsNine(pageId, pageSize, nineCid + "");
		if (goodsNine.getData() != null) {
			goodsNine.getData().getList().forEach(action -> {
				long rebateAmount = CalculateUtil.getRebateAmount(action.getActualPrice(), action.getCommissionRate());
				action.setFcode(rebateAmount);
			});
		}
		return JSON.parseObject(JSON.toJSONString(goodsNine), GoodsNineResp.class);
	}

	@Override
	@RedisPut(db = 11, key = "CAT_DTK_RANK_GOODS_+#key", timeOut = 6000, timeUnit = TimeUnit.SECONDS)
	public List<GoodsRankListResp> dtkRankList(String key, int ctype, String cat) {
//		List<GoodsRankListResp> list = goodsRankDao.list(new GoodsRankListResp(cat, ctype), "dtkRankList");
		// 调用大淘客API查询榜单
		DTKAPI api = DTKAPI.getInstance(0);
		GoodsRank goodsRank = api.getGoodsRankingList(ctype, cat);
		List<GoodsRankListResp> list = new ArrayList<>();
		if (goodsRank.getData() != null) {
			// 计算返利金额
			goodsRank.getData().forEach(good -> {
				good.setFcode(CalculateUtil.getRebateAmount(good.getActualPrice(), good.getCommissionRate()));
			});
			// 转换成响应对象
			list = JSON.parseArray(JSON.toJSONString(goodsRank.getData()), GoodsRankListResp.class);
		}
		return list;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_DTK_GOODS_+#key", timeOut = 6000, timeUnit = TimeUnit.SECONDS)
	public ResultPage<GoodsListResp> dtkGoodsList(String key, String cat, String subcat, int otype, Pages pages) {
		ResultPage<GoodsListResp> listAndPages = glDao.listAndPages(new GoodsListResp(cat, subcat, otype),
				"dtkGoodsList", pages);
		return listAndPages;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_DTK_GOODS_CATS", timeOut = 3, timeUnit = TimeUnit.HOURS)
	public List<Category> getDTKSuperCategory() {
		DTKAPI aDtkapi = DTKAPI.getInstance(0);
		SuperCategory superCategory = aDtkapi.getSuperCategory();
		String data = JSON.toJSONString(superCategory.getData());
		return JSON.parseArray(data, Category.class);
	}

	@Override
	@RedisPut(db = 11, key = "CAT_HOT_SEARCH", timeOut = 30, timeUnit = TimeUnit.MINUTES)
	public List<String> hotSearch() {
		DTKAPI aDtkapi = DTKAPI.getInstance(0);
		List<String> list = aDtkapi.hotSearchList();
		return list;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_SEARCH_WORD_+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public List<Map<String, Object>> getSearchWord(String key, int stype, String kw) {
		DTKAPI aDtkapi = DTKAPI.getInstance(0);
		List<Map<String, Object>> list = aDtkapi.getSearchWord(stype, kw);
		return list;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_GOODS_LIKE_+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public List<GoodsListResp> getGoodsLike(String key, String sid, int size) {
		DTKAPI api = DTKAPI.getInstance(0);
		List<GoodsListResp> resp = api.getGoodsLike(sid, size);
		return resp == null ? new ArrayList<>() : resp;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_GOODS_TOPIC", timeOut = 1, timeUnit = TimeUnit.DAYS)
	public List<Opts> getGoodsTopic() {
		DTKAPI api = DTKAPI.getInstance(0);
		List<Opts> list = api.getGoodsTopic();
		return list;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_GOODS_TOPIC_LIST_+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public GoodsTopicListResp getGoodsTopicList(String key, String topicId, String pageId, int pageSize) {
		DTKAPI api = DTKAPI.getInstance(0);
		GoodsTopicListResp resp = api.getGoodsTopicList(topicId, pageId, pageSize);
		return resp;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_ACTS_LIST", timeOut = 60, timeUnit = TimeUnit.MINUTES)
	public GoodsActivityResp getActs() {
		DTKAPI api = DTKAPI.getInstance(0);
		GoodsActivityResp resp = api.getActs();
		if (resp.getData().size() < 1) {
			String json = "[{\r\n" + "\"activityId\": 6,\r\n" + "\"activityName\": \"双11定金预售\",\r\n"
					+ "\"startTime\": \"2019-10-17 11:13:16\",\r\n" + "\"endTime\": \"2019-11-10 21:59:59\",\r\n"
					+ "\"goodsLabel\": \"https://thumbnail.dataoke.com/img/dtk/market/201910/2019101613543885366198.png\",\r\n"
					+ "\"detailLabel\": \"https://thumbnail.dataoke.com/img/dtk/market/201910/2019101613544427371014.png\",\r\n"
					+ "\"goodsType\": 2\r\n" + "}]";
			List<Activitys> list = JSON.parseArray(json, Activitys.class);
			resp.setData(list);
		}
		return resp;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_ACTS_GOODS_LIST_+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public GoodsActivityListResp getActsGoodsList(String key, String actId, String pageId, int pageSize) {
		DTKAPI api = DTKAPI.getInstance(0);
		GoodsActivityListResp resp = api.getActsGoodsList(actId, pageId, pageSize);
		if ("6".equals(actId)) {
			String jsonData = "{\r\n" + "\"list\":[\r\n" + "{\r\n" + "\"id\": 21623438,\r\n"
					+ "\"goodsId\": \"527388290525\",\r\n" + "\"title\": \"南极人男士内裤男生平角裤衩纯棉潮流个性骚夏天透气薄款四角裤头\",\r\n"
					+ "\"dtitle\": \"南极人男士夏天平角透气个性内裤\",\r\n" + "\"originalPrice\": 49.9,\r\n"
					+ "\"actualPrice\": 29.9,\r\n" + "\"shopType\": 1,\r\n" + "\"goldSellers\": 0,\r\n"
					+ "\"monthSales\": 33448,\r\n" + "\"twoHoursSales\": 0,\r\n" + "\"dailySales\": 0,\r\n"
					+ "\"commissionType\": 3,\r\n"
					+ "\"desc\": \"【南极人品牌】【4条装，赶紧抢】舒适面料，干爽透气，柔软有弹性，柔软亲肤，莫代尔，冰丝都有，轻薄透气，款式多，尺码全。透气性好，不闷热，洗了不褪色，手慢无【赠送运费险】\",\r\n"
					+ "\"couponReceiveNum\": 0,\r\n"
					+ "\"couponLink\": \"https://uland.taobao.com/quan/detail?sellerId=2430420260&activityId=9e40ea87fca441539820e2b22ad7f4bb\",\r\n"
					+ "\"couponEndTime\": \"2019-08-20 23:59:59\",\r\n"
					+ "\"couponStartTime\": \"2019-08-15 00:00:00\",\r\n" + "\"couponPrice\": 20.0,\r\n"
					+ "\"couponConditions\": \"49\",\r\n" + "\"activityType\": 1,\r\n"
					+ "\"createTime\": \"2019-08-14 15:29:08\",\r\n"
					+ "\"mainPic\": \"https://img.alicdn.com/imgextra/i3/4226848392/O1CN01WiDY5H2BraJxnJpp3_!!4226848392.jpg\",\r\n"
					+ "\"marketingMainPic\": \"https://sr.ffquan.cn/relate_pic/o_1di7gdeeb8s2fn1cfq1m5d1g90d.jpg\",\r\n"
					+ "\"sellerId\": \"2430420260\",\r\n" + "\"cid\": 10,\r\n" + "\"discounts\": 0.6,\r\n"
					+ "\"commissionRate\": 20.0,\r\n" + "\"couponTotalNum\": 100000,\r\n" + "\"haitao\": 0,\r\n"
					+ "\"activityStartTime\": \"\",\r\n" + "\"activityEndTime\": \"\",\r\n"
					+ "\"shopName\": \"南极人双鸿专卖店\",\r\n" + "\"shopLevel\": 16,\r\n" + "\"descScore\": 4.8,\r\n"
					+ "\"brand\": 1,\r\n" + "\"brandId\": 107380,\r\n" + "\"brandName\": \"南极人\",\r\n"
					+ "\"hotPush\": 0,\r\n" + "\"teamName\": \"德合联盟\",\r\n"
					+ "\"itemLink\": \"https://detail.tmall.com/item.htm?id=527388290525\",\r\n"
					+ "\"tchaoshi\": 0,\r\n" + "\"detailPics\": \"\",\r\n" + "\"dsrScore\": -1,\r\n"
					+ "\"dsrPercent\": -1,\r\n" + "\"shipScore\": -1,\r\n" + "\"shipPercent\": -1,\r\n"
					+ "\"serviceScore\": -1,\r\n" + "\"servicePercent\": -1,\r\n" + "\"subcid\": [97426],\r\n"
					+ "\"tbcid\": 50008882,\r\n" + "\"quanMLink\":10,\r\n" + "\"hzQuanOver\":100,\r\n"
					+ "\"yunfeixian\":1,\r\n" + "\"estimateAmount\":0\r\n" + "}],\r\n" + "\"totalNum\":16499,\r\n"
					+ "\"pageId\":\"76679471048598b0\"\r\n" + "}";
			Data data = JSON.parseObject(jsonData, GoodsActivityListResp.Data.class);
			resp.setData(data);
			resp.setMsg("成功");
		}
		return resp;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_ZERO_GOODS_LIST_+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public ResultPage<TKSelectionResp> getZoroGoodsList(String key, String cid, int sex, Pages pages) {
		TBAPI tbapi = TBAPI.getInstance(TBAPI.DEFAULT_TYPE);
		ResultPage<TKSelectionResp> resp = tbapi.getTbkUatmFavoritesItem(Long.parseLong(cid), pages);
		return filterGoods(resp);
	}

	@Override
	@RedisPut(db = 11, key = "CAT_THREE_GOODS_LIST_+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public ResultPage<TKSelectionResp> getThreeGoodsList(String key, String cid, int sex, Pages pages) {
		TBAPI tbapi = TBAPI.getInstance(TBAPI.DEFAULT_TYPE);
		ResultPage<TKSelectionResp> resp = tbapi.getTbkUatmFavoritesItem(Long.parseLong(cid), pages);
		return filterGoods(resp);
	}

	@Override
	@RedisPut(db = 11, key = "CAT_FIFTEEN_GOODS_LIST_+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public ResultPage<TKSelectionResp> getFifteenGoodsList(String key, String cid, int sex, Pages pages) {
		TBAPI tbapi = TBAPI.getInstance(TBAPI.DEFAULT_TYPE);
		ResultPage<TKSelectionResp> resp = tbapi.getTbkUatmFavoritesItem(Long.parseLong(cid), pages);
		if (resp != null && resp.getList() != null) {
			resp.getList().forEach(item -> {
				item.setFcode(0);
			});
		}
		return filterGoods(resp);
	}

	@Override
	public boolean getTodayCatDevRemitInfoResp(String pid, int... rtypeArray) {
		// 根据用户ID查询用户提现记录
		CatDevRemitRecordResp remitInfoResp = new CatDevRemitRecordResp(pid);
		remitInfoResp.setRtypeArray(rtypeArray);
		CatDevRemitRecordResp infoResp = remitDao.selectOne(remitInfoResp, "getLastTimeRemit");
		// 如果未有提现记录，则直接返回false
		if (infoResp == null) {
			return false;
		}
		// 获取上次提现时间
		Date date = DateAPIUtils.stringToDate(infoResp.getCtime(), DateAPIUtils.YYYYMMDDHHMMSS);
		if (date == null) {
			log.error("getTodayCatDevRemitInfoResp error：pid=" + pid + "时间格式错误");
		} else {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.DAY_OF_MONTH, +1);
			// 对比与上次提现时间是否大于一天
			if (calendar.getTime().getTime() <= System.currentTimeMillis()) {
				return false;
			}
		}
		return true;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_DAILY_SURPRISE_GOODS_LIST_+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public ResultPage<TKSelectionResp> getDailySurpriseGoodsList(String key, String cid, Integer sex, Pages pages) {
		TBAPI tbapi = TBAPI.getInstance(TBAPI.DEFAULT_TYPE);
		ResultPage<TKSelectionResp> resp = tbapi.getTbkUatmFavoritesItem(Long.parseLong(cid), pages);
		return filterGoods(resp);
	}

	@Override
//	@RedisPut(db = 11, key = "CAT_CVS_DAILY_BAG_+#pid+_+#time", timeOut = 1, timeUnit = TimeUnit.DAYS)
	public CVSDrawHistory getCVSDailySuprise(String time, String pid) {
		return cddao.selectOne(new CVSDrawHistory(pid), "getTodayLiBao");
	}

	@Override
//	@RedisPut(db = 11, key = "CAT_GAME_FRUIT_PRINCE_LIST", timeOut = 1, timeUnit = TimeUnit.HOURS)
	public List<FruitPrinceInfoResp> getFruitPrinceInfo() {
		return fpdao.list(new FruitPrinceInfoResp(), "getOnlineFruitPrinceList");
	}

	@Override
	public CardDrawCountHistoryResp getCardDrawCount(String pid) {
		CardDrawCountHistoryResp result = null;
		CardDrawCountHistory resultEntity = null;
		CardDrawCountHistory result_1 = cardDrawCountHistoryRepository.findByPidAndCtimeAndDtype(pid,
				LocalDate.now().toString(), 1);
		/* 已使用刮卡次数 */
		int result_0_count = 0;
		if (result_1 == null) {
			result_1 = new CardDrawCountHistory(LocalDate.now().toString(), pid, 1, 20,
					LocalDate.now().toString() + " " + getSendCardTime(0));
			resultEntity = cardDrawCountHistoryRepository.saveAndFlush(result_1);
		} else {
			/* 剩余刮卡次数 */
			int lastCardCount = 0;
			resultEntity = result_1;

			CardDrawCountHistory result_0 = cardDrawCountHistoryRepository.findByPidAndCtimeAndDtype(pid,
					LocalDate.now().toString(), -1);
			if (result_0 != null) {
				result_0_count = result_0.getDcount();
			}

			lastCardCount = result_1.getDcount() - result_0_count;
			if (lastCardCount < 20) {
				if ((TJKUtils.parse2LocalDateTime(result_1.getLtime()).getHour() == 0
						&& LocalDateTime.now().getHour() >= 8)
						|| (TJKUtils.parse2LocalDateTime(result_1.getLtime()).getHour() == 8
								&& LocalDateTime.now().getHour() >= 12)
						|| (TJKUtils.parse2LocalDateTime(result_1.getLtime()).getHour() == 12
								&& LocalDateTime.now().getHour() >= 17)
						|| (TJKUtils.parse2LocalDateTime(result_1.getLtime()).getHour() == 17
								&& LocalDateTime.now().getHour() >= 20)) {
					int addCardNum = 0;
					/* 补充刮刮卡10次 */
					if (lastCardCount + 10 > 20) {
						addCardNum = (20 - lastCardCount);
						result_1.setDcount(result_1.getDcount() + (20 - lastCardCount));
					} else {
						addCardNum = 10;
						result_1.setDcount(result_1.getDcount() + 10);
					}

					// 查询今日刮卡抽奖banner数据
					List<CardDrawBannerResp> list = cardDrawBannerRespDao.list(new CardDrawBannerResp(pid, 0),
							"getCardBannerList");
					// 判断是否为今天发的banner数据
					if (list != null && list.size() > 0 && list.get(0).getCtime().equals(LocalDate.now().toString())) {
						// 更新的集合
						List<CardDrawEntryInfo> bannerList = new ArrayList<>();
						// 是否为每日限量，如果为每日限量的刮刮卡则不再发卡
						int isDailyLimit = 0;

						// 更新刮刮卡banner列表
						for (int i = 0; i < (addCardNum + isDailyLimit) && i < list.size(); i++) {
							// 如果为每日限量卡，则不再进行发卡
							if (list.get(i).getGtype() == 12) {
								isDailyLimit++;
								break;
							}
							list.get(i).setStatus(1);
							list.get(i).setGcards(0);
							list.get(i).setLtime(TJKUtils.DateTime());

							bannerList.add(JSON.parseObject(JSON.toJSONString(list.get(i)), CardDrawEntryInfo.class));
						}
//						List<CardDrawEntryInfo> bannerList = JSON.parseArray(JSON.toJSONString(list), CardDrawEntryInfo.class);
						// 插入
						if (cardDrawEntryInfoDao.update(bannerList, "updateStatus") == false) {
							log.error("getCardBanner:pid=" + pid + "刮刮卡banner数据更新失败！");
							return null;
						}
					}

					if (LocalDateTime.now().getHour() < 8) {
						result_1.setLtime(LocalDate.now().toString() + " 00:00:00");
					} else if (LocalDateTime.now().getHour() < 12) {
						result_1.setLtime(LocalDate.now().toString() + " 08:00:00");
					} else if (LocalDateTime.now().getHour() < 17) {
						result_1.setLtime(LocalDate.now().toString() + " 12:00:00");
					} else if (LocalDateTime.now().getHour() < 20) {
						result_1.setLtime(LocalDate.now().toString() + " 17:00:00");
					}
					resultEntity = cardDrawCountHistoryRepository.saveAndFlush(result_1);
				}
			}

		}
		int resultDcount = resultEntity.getDcount() - result_0_count;

		result = new CardDrawCountHistoryResp(resultDcount, resultEntity.getLtime());
		return result;
	}

	/**
	 * 获取下一次发卡时间
	 * 
	 * @param type 0.上次发卡时间、1.下次发卡时间
	 * @return
	 */
	private String getSendCardTime(int type) {
		// 配置发卡时间
		String[] timeArray = { "00:00:00", "08:00:00", "12:00:00", "17:00:00", "20:00:00" };

		// 设置下次发卡时间
		Calendar calendar = Calendar.getInstance();
		int hour = calendar.get(Calendar.HOUR_OF_DAY);

		// 遍历查找下次发卡时间
		for (int i = 0; i < timeArray.length; i++) {
			if (i != timeArray.length - 1) {
				int time1 = Integer.parseInt(timeArray[i].substring(0, 2));
				int time2 = Integer.parseInt(timeArray[i + 1].substring(0, 2));
				if (hour >= time1 && hour < time2) {
					return type == 0 ? timeArray[i] : timeArray[i + 1];
				}
			} else {
				return type == 0 ? timeArray[i] : timeArray[0];
			}
		}
		return null;
	}

	@Override
	public List<CardNewHistory> getCardNewHistory(String pid, CatDevUserInfo devInfo) {
		List<CardNewHistory> newHistory = cardNewHistoryRepository.findByPidOrderByDays(pid);
//		CatDevUserInfo devInfo = getCatDevUserInfoByPid(pid);
		if (devInfo != null && devInfo.getCtime() != null) {
			log.info("-newHistory-1->");
			/* 七天已过，新人专享礼物已过期 */
			if (LocalDate.now().isAfter(TJKUtils.parse2LocalDate(devInfo.getCtime()).plusDays(6))) {
				return null;
			} else {
				log.info("-newHistory-2->");
				/* 注册后第N天 */
				int days = (int) (LocalDate.now().toEpochDay()
						- TJKUtils.parse2LocalDate(devInfo.getCtime()).toEpochDay() + 1);
				/* 注册后第一次进入，初始化新人专享礼物信息 */
				if (newHistory == null || newHistory.isEmpty()) {
					log.info("-newHistory-3->");
					newHistory = new ArrayList<CardNewHistory>();
					for (int i = 0; i < 7; i++) {
						int dcount = 0;
						int dstatus = 0;
						if (i + 1 == days) {
							dstatus = 1;
						}
						if (i + 1 < 3 || (i + 1 < 7 && i + 1 > 3)) {
							dcount = 100;
						} else if (i + 1 == 3) {
							dcount = 500;
						} else if (i + 1 == 7) {
							dcount = 1888;
						}
						CardNewHistory insert = new CardNewHistory(pid, i + 1,
								TJKUtils.parse2LocalDate(devInfo.getCtime()).plusDays(i).toString(), dcount, dstatus,
								TJKUtils.DateTime());
						newHistory.add(insert);
						log.info("-newHistory-->" + newHistory.size());
					}

					if (cardNewHistoryRepository.saveAll(newHistory) != null) {
						log.info("-saveAll-success->" + newHistory.size());
					} else {
						log.info("-saveAll-error->" + newHistory.size());
					}
				} else {
					CardNewHistory updHistory = cardNewHistoryRepository.findByPidAndDays(pid, days);
					if (updHistory != null && updHistory.getDstatus() == 0) {
						updHistory.setDstatus(1);
						updHistory.setLtime(TJKUtils.DateTime());
						cardNewHistoryRepository.saveAndFlush(updHistory);
					}
				}
			}
		}
		return newHistory;
	}

	@Override
	public int getCardPokerCount(String pid) {
		int result = 0;
		CardPokerDrawCountHistory poker_1 = cardPokerDrawCountHistoryRepository.findByPidAndCtimeAndDtype(pid,
				LocalDate.now().toString(), 1);
		if (poker_1 == null) {
			poker_1 = new CardPokerDrawCountHistory(LocalDate.now().toString(), pid, 1, 50, TJKUtils.DateTime());
			if (cardPokerDrawCountHistoryRepository.saveAndFlush(poker_1) != null) {
				result = 50;
			}
		} else {
			CardPokerDrawCountHistory poker_0 = cardPokerDrawCountHistoryRepository.findByPidAndCtimeAndDtype(pid,
					LocalDate.now().toString(), -1);
			if (poker_0 != null) {
				result = poker_1.getDcount() - poker_0.getDcount();
			} else {
				result = poker_1.getDcount();
			}
		}
		return result < 0 ? 0 : result;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_SHOP_GOODS_LIKE_+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public List<ZTKShopResp> getZTKShopLike(String key, String imei, String sid, String idfa, int page, int pageSize) {
		ZTKAPI ztkapi = ZTKAPI.getInstance(0);
		ZTKShopDetail shopLike = ztkapi.getShopLike("new", sid, imei, idfa, page, pageSize);
		List<ZTKShopResp> resp = JSON.parseArray(JSON.toJSONString(shopLike.getContent()), ZTKShopResp.class);
		// 重新计算返佣金额
		resp.forEach(item -> {
			double amount = item.getTkfee3();
			if (amount > 0 && amount <= 3) {
				item.setTkfee3((long) (amount * 0.35 * 100));
			} else if (amount > 3 && amount <= 8) {
				item.setTkfee3((long) (amount * 0.32 * 100));
			} else {
				item.setTkfee3((long) (amount * 0.28 * 100));
			}
		});

		return resp;
	}

	@Override
	public long getCatDevLastBeans(String pid) {
		CatDevUserInfoResp resultEntity = catDao.selectOne(new CatDevUserInfo(pid, pid), "getCatDevLastBeans");
		if (resultEntity != null) {
			return resultEntity.getBeans() < 0 ? 0 : resultEntity.getBeans();
		}
		return 0;
	}

	@Override
	public long getCatDevBeansByGame(String pid) {
		CatDevUserInfoResp resultEntity = catDao.selectOne(new CatDevUserInfo(pid, pid), "getCatDevBeansByGame");
		if (resultEntity != null) {
			return resultEntity.getBeans() < 0 ? 0 : resultEntity.getBeans();
		}
		return 0;
	}

	@Override
	public CatDevUserInfoResp getCatDevBeansData(String pid) {
		CatDevUserInfoResp resultEntity = catDao.selectOne(new CatDevUserInfo(pid), "getCatDevBeansData");
		return resultEntity == null ? new CatDevUserInfoResp() : resultEntity;

	}

	@Override
	public long getCatDevLastRMB(String pid) {
		CatDevUserInfoResp resultEntity = catDao.selectOne(new CatDevUserInfo(pid, pid), "getCatDevLastRMB");
		if (resultEntity != null) {
			return resultEntity.getRpt() < 0 ? 0 : resultEntity.getRpt();
		}
		return 0;
	}

	@Override
	public CashBalanceInfo getUserBalance(String pid) {
		CashBalanceInfo resultEntity = cashBalanceInfoDao.selectOne(new CatDevUserInfo(pid, pid), "getUserBalance");
		if (resultEntity == null) {
			resultEntity = new CashBalanceInfo();
			resultEntity.setOrderRebate(0);
			resultEntity.setReadyRebate(0);
			resultEntity.setRedPacketBalance(0);
		}
		return resultEntity;
	}

	@Override
	public CatDevUserInfoResp getCatDevIncomeInfo(String pid) {
		CatDevUserInfoResp result = catDao.selectOne(new CatDevUserInfo(pid, pid), "getIncomeInfo");
		if (result != null) {
			if (result.getRpt() < 0) {
				result.setRpt(0);
			}
			if (result.getBeans() < 0) {
				result.setBeans(0);
			}
		}
		return result;
	}

	@Override
	public CatDevWeInfo getWxInfoByCode(int rtype, String code, int type, String vscode, String cid) {
		String appid;
		String secret;
		switch (type) {
		case 0:
			appid = configs.getWeappid();
			secret = configs.getWesecret();
			break;
		case 1:
			if (Integer.parseInt(vscode) == 10 && !cid.equals("ym-vivo") && !cid.equals("ym-samsung")
					&& !cid.equals("ym-aliyun")) {
				appid = configs.getWeChatAppid();
				secret = configs.getWeChatSecret();
			} else {
				appid = configs.getTtjWxAppid();
				secret = configs.getTtjWxSecret();
			}
			break;
		case 2:
			appid = configs.getYtWxAppid();
			secret = configs.getYtWxSecret();
			break;
		case 101:
			appid = configs.getWxAppid();
			secret = configs.getWxSecret();
			break;
		default:
			appid = configs.getWeappid();
			secret = configs.getWesecret();
			break;
		}
		return requestGetWxInfo(code, appid, secret);
	}

	/*
	 * 获取微信用户信息
	 */
	private CatDevWeInfo requestGetWxInfo(String code, String appId, String secret) {
		CatDevWeInfo result = null;
		LocalDateTime startTime = LocalDateTime.now();
		/* 根据code获取access_token */
		String access_token_json, access_token, openid;
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
		Map<String, String> params = new HashMap<String, String>();
		params.put("appid", appId);
		params.put("secret", secret);
		params.put("code", code);
		params.put("grant_type", "authorization_code");
		try {
			access_token_json = WebUtils.doGet(url, params);
			log.info("-get_access_token-->" + access_token_json);
		} catch (IOException e) {
			return null;
		}
		LocalDateTime endtTime = LocalDateTime.now();
		Duration between = Duration.between(startTime, endtTime);
		if (between.getSeconds() > 6) {
			log.error("获取微信access_token超时:" + between.toMillis());
		}
		startTime = LocalDateTime.now();
		if (!access_token_json.contains("access_token")) {
			access_token_json = null;
		}
		if (JSONObject.isValidObject(access_token_json)) {
			JSONObject access_token_object = JSONObject.parseObject(access_token_json);
			access_token = access_token_object.getString("access_token");
			openid = access_token_object.getString("openid");
			/* 根据access_token获取微信信息 */
			if (StringUtils.isNotBlank(access_token)) {
				url = "https://api.weixin.qq.com/sns/userinfo";
				params = new HashMap<String, String>();
				params.put("openid", openid);
				params.put("access_token", access_token);
				try {
					access_token_json = WebUtils.doGet(url, params);
					log.info("-get_userinfo-->" + access_token_json);
				} catch (IOException e) {
					return null;
				}
				if (JSONObject.isValidObject(access_token_json)) {
					result = JSONObject.parseObject(access_token_json, CatDevWeInfo.class);
				}
				// 将性别标识与九趣猫统一,微信返回普通用户性别，1 为男性，2 为女性
				result.setSex(result.getSex() == 2 ? 0 : 1);
				endtTime = LocalDateTime.now();
				between = Duration.between(startTime, endtTime);
				if (between.getSeconds() > 6) {
					log.error("获取微信userinfo超时:" + between.toMillis());
				}
			}
		}
		return result;
	}

	@Override
	public long getInviteNewUserIncome(String pid) {
		Long income = longDao.selectOne(new CatDevZJInviteInfoResp(pid), "getInviteNewUserIncome");
		return income == null ? 0 : income;
	}

	@Override
	@RedisPut(rtype = 2, db = 11, key = "CAT_APP_DEVICE", hashKey = "+#key", timeOut = 10, timeUnit = TimeUnit.DAYS)
	public Boolean IsNewDevice(String key) {
		List<CatAppNewDeviceInfo> results = catAppNewDeviceInfoRepository.findNewById(key);
		if (results == null || results.isEmpty()) {
			return null;
		}
		return false;
	}

	@Override
	@RedisPut(rtype = 2, db = 11, key = "CAT_APP_ACT_DEVICE", hashKey = "+#key", timeOut = 1, timeUnit = TimeUnit.DAYS)
	public Boolean IsActivedDevice(String key) {
		if (redis11.opsForHash().hasKey("CAT_APP_ACT_DEVICE", key)) {
			return false;
		}
		Set<Object> hkeys = redis11.opsForHash().keys("CAT_APP_ACT_DEVICE");
		log.info("--->" + hkeys.size());
		List<Object> hklist = hkeys.stream().filter(new Predicate<Object>() {
			@Override
			public boolean test(Object t) {
				String[] hks = t.toString().split("_");
				String time = hks[hks.length - 1];
				log.info("--time->" + time);
				return TJKUtils.parse2LocalDate(time).isBefore(LocalDate.now().minusDays(6));
			}

		}).collect(Collectors.toList());

		if (hklist != null && LocalDateTime.now().getHour() > 13) {
			redis11.executePipelined(new RedisCallback<Long>() {
				public Long doInRedis(RedisConnection connection) throws DataAccessException {
					connection.openPipeline();
					hklist.forEach(hkey -> {
						if (!hkey.toString().contains(LocalDate.now().toString())) {
							connection.hDel("CAT_APP_ACT_DEVICE".getBytes(), hkey.toString().getBytes());
						}
					});
					return null;
				}
			});
		}
		redis11.opsForHash().put("CAT_APP_ACT_DEVICE", key, false);
		return null;

	}

	@Override
	public CatDevBeanVideoHistoryResp getBeanVideoHistory(String pid, int ltype) {
		// 获取今日观看视频次数及最后一次领取的时间
		return beanVideoHistoryRespDao.selectOne(new CatDevBeanVideoHistoryResp(pid, ltype), "getBeanVideoData");
	}

	@Override
	@RedisPut(db = 11, key = "CAT_BANNER_GOODS_LIST_+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public ResultPage<TKSelectionResp> getBannerGoodsList(String key, String fid, Pages pages) {
		TBAPI tbapi = TBAPI.getInstance(TBAPI.DEFAULT_TYPE);
		ResultPage<TKSelectionResp> resp = tbapi.getTbkUatmFavoritesItem(Long.parseLong(fid), pages);
		return filterGoods(resp);
	}

//	@Override
//	@RedisPut(rtype = 2, db = 14, key = "CAT_APP_PV_MENUS", hashKey = "+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
//	public List<CatAppPvMenus> getAppPVMenus(String key, String mid, String cmid) {
//		List<CatAppPvMenus> result = new ArrayList<CatAppPvMenus>();
//		if (StringUtils.isBlank(mid) || "0".equals(mid)) {
//			result = catAppPvMenusRepository.findByMidLessThanEqualOrderByMidAsc("106");
//		} else {
//			if (StringUtils.isBlank(cmid) || "0".equals(cmid)) {
//				result = catAppPvMenusRepository.findByMidOrderByMidAsc(mid);
//			} else {
//				result = catAppPvMenusRepository.findByMidAndCmidOrderByMidAsc(mid, cmid);
//			}
//		}
//		if (result == null || result.isEmpty()) {
//			return null;
//		}
//		return result;
//	}

	@Override
	@SuppressWarnings("unchecked")
//	@RedisPut(db = 11, key = "CAT_FLASH_SALE_GOODS_LIST_+#currentDate", timeOut = 2, timeUnit = TimeUnit.DAYS)
	public List<FlashSaleGoodsResp> getFlashSaleGoodsList(String currentDate) {
		String key = "CAT_FLASH_SALE_GOODS_LIST";
		// 查询限时抢购商品库信息
		Map<String, Integer> goodsIndexMap = new HashMap<>();
		// 商品页数指针
		Integer goodsPageIndex = null;
		// 商品页数15分页每三条为一段,论断取值，一页15共有5段
		Integer goodsSubIndex = null;
		// 响应数据
		List<FlashSaleGoodsResp> qgList;
		// 判断是否数据发生变化,默认未发生变化
		boolean isChange = false;

		// 获取限时抢购信息
		List<FlashSaleGoodsResp> list;

		// 判断缓存中是否存在
		if (redis11.hasKey(key)) {
			// 获取限时抢购信息
			list = (List<FlashSaleGoodsResp>) redis11.opsForValue().get(key);
			// 创建检测数据变化对象
			List<FlashSaleGoodsResp> testList = JSON.parseArray(JSON.toJSONString(list), FlashSaleGoodsResp.class);

			// 获取当前抢购时间段信息
			qgList = queryFlashSaleDataList(null);

			// 判断第一个时间是否相等，如果相等则直接返回从Redis获取的值
			if (qgList.get(0).getStartTime().equals(list.get(0).getStartTime())) {
				FlashSaleGoodsResp qgGoodsResp, redisGoodsResp;
				for (int i = 0; i < qgList.size(); i++) {
					qgGoodsResp = qgList.get(i);
					redisGoodsResp = list.get(i);
					redisGoodsResp.setStatus(
							redisGoodsResp.getStatus() != 2 ? qgGoodsResp.getStatus() : redisGoodsResp.getStatus());
					qgList.get(i).setList(redisGoodsResp.getList());
				}
			} else {
				// 数据已改变
				isChange = true;
				// 将Redis中的数据由时间为key转成map对象
				Map<String, FlashSaleGoodsResp> collect = list.stream()
						.collect(Collectors.toMap(FlashSaleGoodsResp::getStartTime, resp -> {
							return resp;
						}));

				List<FlashSaleGoods> respList = new ArrayList<>();

				// 获取分页指针标识
				goodsIndexMap = (Map<String, Integer>) redis11.opsForValue().get(key + "_INDEX");
				goodsPageIndex = goodsIndexMap.get("goodsPageIndex");
				goodsSubIndex = goodsIndexMap.get("goodsSubIndex");

				goodsPageIndex = goodsPageIndex == null ? 1 : goodsPageIndex;
				goodsSubIndex = goodsSubIndex == null ? 1 : goodsSubIndex;

				FlashSaleGoodsResp info;
				for (int i = 0; i < qgList.size(); i++) {
					info = qgList.get(i);
					FlashSaleGoodsResp goodsResp = collect.get(info.getStartTime());
					if (goodsResp != null) {
						goodsResp.setStatus(goodsResp.getStatus() != 2 ? info.getStatus() : goodsResp.getStatus());
						info = goodsResp;
						qgList.get(i).setList(goodsResp.getList());
					} else {
						// 获取新的时间段的商品数据
						respList = getFlashSaleGoods(respList, goodsPageIndex);
						if (respList.size() < 15) {
							// 当数据返回不了一页数据时,将页码重置到1,
							goodsPageIndex = 1;
							// 重置为第一段数据
							goodsSubIndex = 1;
							respList = getFlashSaleGoods(respList, goodsPageIndex);
						} else if (respList.size() >= 15 && goodsSubIndex == 6) {
							// 数据不够时，进入下一页查询
							goodsPageIndex++;
							// 重置为第一段数据
							goodsSubIndex = 1;
							respList = getFlashSaleGoods(respList, goodsPageIndex);
						}
						info.setList(new ArrayList<>(
								respList.subList((goodsSubIndex - 1) * 3, (goodsSubIndex - 1) * 3 + 3)));
						for (FlashSaleGoods flashSaleGoods : info.getList()) {
							flashSaleGoods.setGoodsStatus(info.getStatus() == 1 ? 1 : 0);
							flashSaleGoods.setZkFinalPrice("1");
							flashSaleGoods.setTotalAmount(100L);
						}
						goodsSubIndex++;
					}
				}
			}

			// 判断从Redis中获取的集合数据是否发生变化
			isChange = isChange == false ? !testList.equals(list) : isChange;
		} else {
			goodsPageIndex = 1;
			// 缓存中不存在则创建
			final List<FlashSaleGoods> respList = new ArrayList<>();
			// 从选品库中获取抢购商品
			getFlashSaleGoods(respList, goodsPageIndex);
			// 第一页已使用完,增加一页
			goodsPageIndex = 2;
			// 设置取商品列表的逻辑
			ExtendMethod<List<FlashSaleGoods>, Integer> method = new ExtendMethod<List<FlashSaleGoods>, Integer>() {

				@Override
				public List<FlashSaleGoods> executeMethod(Integer i) {
					List<FlashSaleGoods> qgGoods;
					// 设置抢购商品数据
					if (respList.size() >= ((i + 1) * 3)) {
						qgGoods = new ArrayList<>(respList.subList(i * 3, ((i + 1) * 3)));
					} else if (respList.size() > i * 3) {
						qgGoods = new ArrayList<>(respList.subList(i * 3, respList.size()));
					} else {
						qgGoods = new ArrayList<>();
					}
					return qgGoods;
				}
			};

			qgList = queryFlashSaleDataList(method);
			isChange = true;
		}
		// 开抢后1分钟、3、7分钟调整一次抢购数量信息
		for (FlashSaleGoods item : qgList.get(0).getList()) {
			if (item.getSoldNum().intValue() != item.getTotalAmount().intValue()) {
				item.setSoldNum(item.getTotalAmount());
				// 标识为已抢光
				item.setGoodsStatus(2);
				isChange = true;
			}
		}
//		LocalDateTime startTime = TJKUtils.parse2LocalDateTime(qgList.get(0).getStartTime()+":00");
//		Duration duration=Duration.between(startTime, LocalDateTime.now());
//		if (duration.toMinutes()>=7 && qgList.get(0).getList().get(0).getSoldNum()<100) {
//			qgList.get(0).getList().forEach(item->{
//				item.setSoldNum(item.getTotalAmount());
//				//标识为已抢光
//				item.setGoodsStatus(2);
//			});
//			isChange=true;
//		}else if (duration.toMinutes()>3  && qgList.get(0).getList().get(0).getSoldNum()<40) {
//			qgList.get(0).getList().forEach(item->{
//				item.setSoldNum(item.getSoldNum()+RandomUtils.nextInt(20, 30));
//			});
//			isChange=true;
//		}else if (duration.toMinutes()>=1 && qgList.get(0).getList().get(0).getSoldNum()<20) {
//			qgList.get(0).getList().forEach(item->{
//				item.setSoldNum(item.getSoldNum()+RandomUtils.nextInt(20, 30));
//			});
//			isChange=true;
//		}

		// 判断商品数据是否有变化
		if (isChange) {
			// 存入缓存
			redis11.opsForValue().set(key, qgList);
		}

		if (goodsPageIndex != null) {
			goodsIndexMap.put("goodsPageIndex", goodsPageIndex);
		}
		if (goodsSubIndex != null) {
			goodsIndexMap.put("goodsSubIndex", goodsSubIndex);
		}
		if (goodsIndexMap.size() > 0) {
			// 将分页页码存入记录
			redis11.opsForValue().set(key + "_INDEX", goodsIndexMap);
		}

		return qgList;
	}

	/**
	 * 获取抢购信息列表
	 * 
	 * @author lipengchao
	 * @date 2019-12-10 10:34:55
	 * @param method 遍历过程中需要执行的方法
	 * @return
	 */
	private List<FlashSaleGoodsResp> queryFlashSaleDataList(ExtendMethod<List<FlashSaleGoods>, Integer> method) {
		List<FlashSaleGoodsResp> qgList = new ArrayList<>();
		// 抢购时间点，10:00、12:00、16:00、20:00、22:00
		int[] qgTimeArray = { 10, 12, 16, 20, 22 };

		// 获取当前抢购时间段
		int currentTimeSlot = 0, index = 0;

		// 获取当前时间
		int currentHour = LocalTime.now().getHour();
		// 获取当前所处时间段
		for (int i = 0; i < qgTimeArray.length; i++) {
			if (i == qgTimeArray.length - 1 || (qgTimeArray[i] <= currentHour && currentHour < qgTimeArray[i + 1])) {
				currentTimeSlot = qgTimeArray[i];
				index = i;
				break;
			}
		}

		// 抢购状态,下一天标识
		int status = 0;
		// 抢购时间
		String qgTime;
		FlashSaleGoodsResp qgGoods;
		for (int i = 0; i < qgTimeArray.length; i++) {
			qgGoods = new FlashSaleGoodsResp();

			// 如果index达到数组的长度则说明到下一天时间
			if (index == qgTimeArray.length) {
				index = 0;
				// 判断当前时间,如果当前时间小于每天的首个开抢时间则说明还没有第二天的抢购信息
				status = LocalDateTime.now().getHour() < qgTimeArray[0] ? 0 : 2;
			} else if (currentTimeSlot == qgTimeArray[index]) {
				// 正在抢购
				status = 1;
			} else {
				// 如果不是下一天的时间则为未开抢(即将开抢)
				status = status == 2 ? status : 0;
			}
			// 设置抢购状态值
			qgGoods.setStatus(status);
			// 设置抢购时间
			if (status == 2) {
				// 明天的时间
				qgTime = LocalDate.now().plusDays(1).toString() + " "
						+ LocalTime.of(qgTimeArray[index], 0, 0).toString();
			} else {
				qgTime = LocalDate.now().toString() + " " + LocalTime.of(qgTimeArray[index], 0, 0).toString();
			}
			qgGoods.setStartTime(qgTime);

			if (method != null) {
				qgGoods.setList(method.executeMethod(i));
				for (FlashSaleGoods item : qgGoods.getList()) {
					// 标示为正在抢购
					item.setGoodsStatus(status == 1 ? 1 : 0);
					item.setZkFinalPrice("1");
					item.setTotalAmount(100L);
				}
			}
			qgList.add(qgGoods);
			index++;
		}
		return qgList;
	}

	private List<FlashSaleGoods> getFlashSaleGoods(List<FlashSaleGoods> flashSaleGoods, Integer goodsPageIndex) {
		if (flashSaleGoods != null && flashSaleGoods.size() >= 15) {
			return flashSaleGoods;
		}
		flashSaleGoods.clear();
		// 从选品库中获取抢购商品
		TBAPI tbapi = TBAPI.getInstance(TBAPI.DEFAULT_TYPE);
		Pages pages = new Pages(goodsPageIndex, 15);
		// 获取限时抢购选品库ID
		List<Map<String, String>> favoritesList = getFavoritesList(6);
		// 调用查询接口
		ResultPage<TKSelectionResp> resp = tbapi
				.getTbkUatmFavoritesItem(Long.parseLong(favoritesList.get(0).get("cid")), pages);
		if (resp != null && resp.getList() != null && resp.getList().size() > 0) {
			flashSaleGoods.addAll(JSON.parseArray(JSON.toJSONString(resp.getList()), FlashSaleGoods.class));
		}
		return flashSaleGoods;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_FLASH_LOWER_GOODS_LIST_+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public ResultPage<TKSelectionResp> getFlashLowerGoodsList(String key, Integer sex, Pages pages) {
		TBAPI tbapi = TBAPI.getInstance(TBAPI.DEFAULT_TYPE);
		List<Map<String, String>> favoritesList = getFavoritesList(5);
		if (favoritesList == null || favoritesList.size() < 1) {
			return null;
		}
		String fid = favoritesList.get(0).get("cid");
		ResultPage<TKSelectionResp> resp = tbapi.getTbkUatmFavoritesItem(Long.parseLong(fid), pages);
		return filterGoods(resp);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Boolean rushToBuySaleGoods(String pid, String sid) {
		String key = "CAT_FLASH_SALE_GOODS_LIST";
		if (redis11.hasKey(key)) {
			// 获取限时抢购信息
			List<FlashSaleGoodsResp> dataList = (List<FlashSaleGoodsResp>) redis11.opsForValue().get(key);
			dataList.get(0).getList().forEach(goods -> {
				if (StringUtils.equals(sid, goods.getNumIid() + "") && goods.getGoodsStatus() != 2) {
					goods.setGoodsStatus(2);
					goods.setSoldNum(100L);
					// 保存抽奖概率
					redis11.opsForValue().set(key, dataList);
				}
			});
		}
		return true;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_USER_ORDER_NUMBER_+#pid", timeOut = 10, timeUnit = TimeUnit.DAYS)
	public Integer getUserOrderNumber(String pid) {
		// 查询15元补贴用户订单数量
		Integer count = intDao.selectOne(new CatDevOrderResp(pid, 0, 10), "getFifteenOrderCountByPid");
		return count == 0 ? null : count;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_ORDER_NUMBER_+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public Integer getOrderNumber(String key,String pid, String ctime) {
		// 查询有效订单数量
		Integer count = intDao.selectOne(CatDevOrderResp.builder().pid(pid).ctime(ctime).build(), "getOrderCount");
		return count == 0 ? null : count;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_SCROLL_BAR_DATA_+#stype+_+#dtype", timeOut = 1, timeUnit = TimeUnit.DAYS)
	public List<String> getScrollBarInfoData(int stype, int dtype) {
		List<CatScrollBarInfo> list = catScrollBarInfoRepository.findByStypeAndDtype(stype, dtype);
		List<String> collect = list.stream().map(CatScrollBarInfo::getContent).collect(Collectors.toList());
		return collect;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_CARD_SCROLL_BAR_DATA", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public List<ScrollBarInfoResp> getCardScrollBarList() {
		// 获取所有的昵称
		List<String> nicknameList = getScrollBarInfoData(0, 0);
		// 获取所有的头像
		List<String> iconList = getScrollBarInfoData(0, 1);
		// 组合拼接
		List<ScrollBarInfoResp> resultList = new ArrayList<>();
		// 获取刮刮卡奖励金额信息
		List<CardDrawBannerConf> list = cardDrawBannerConfRepository.findAll();
		Random random = new Random();
		Set<String> cardAmountSet = new HashSet<>();
		for (CardDrawBannerConf conf : list) {
			cardAmountSet.add(conf.getAmount());
		}
		List<String> collect = cardAmountSet.stream().collect(Collectors.toList());
		Collections.sort(collect, new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {
				return Integer.parseInt(o1) - Integer.parseInt(o2);
			}
		});
		// 设置比例
		double[] proportions = { 20, 40, 40, 35, 30, 30, 20, 20, 20, 20, 10, 5 };
		StringBuilder builder = new StringBuilder();
		StringBuilder iconBuilder = new StringBuilder();
		for (int i = 0; i < 100; i++) {
			String extract = CalculateUtil.ratioExtract(collect.toArray(new String[collect.size()]), proportions);
			builder.append(nicknameList.get(random.nextInt(nicknameList.size())));
			iconBuilder.append(iconList.get(random.nextInt(iconList.size())));
			resultList.add(new ScrollBarInfoResp(builder.toString(), iconBuilder.toString(), extract));
			builder.setLength(0);
			iconBuilder.setLength(0);
		}
		return resultList;
	}

	@Override
	@RedisPut(db = 2, key = "CAT_TEST_+#key", timeOut = 1, timeUnit = TimeUnit.DAYS)
	public String test(String key) {
		return key;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_FAVORITES_LIST_+#typeId", timeOut = 1, timeUnit = TimeUnit.HOURS)
	public List<Map<String, String>> getFavoritesList(Integer typeId) {
		List<CatGoodsFavoritesInfo> list = catGoodsFavoritesInfoDao.list(new CatGoodsFavoritesInfo(typeId),
				"getFavoritesList");
		List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
		if (list != null) {
			list.forEach(info -> {
				Map<String, String> map = new HashMap<>();
				map.put("cname", info.getName());
				map.put("cid", info.getId() + "");
				resultList.add(map);
			});
		}
		return resultList;
	}

	@Override
	@RedisPut(db = 2, key = "CAT_WECHAT_OPENID_+#code", timeOut = 30, timeUnit = TimeUnit.MINUTES)
	public String getWeChatOpenIdByCode(String code) {
		/* 根据code获取openId */
		String access_token_json, access_token, openid;
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
		Map<String, String> params = new HashMap<String, String>();
		params.put("appid", configs.getWxAppid());
		params.put("secret", configs.getWxSecret());
		params.put("code", code);
		params.put("grant_type", "authorization_code");
		try {
			access_token_json = WebUtils.doGet(url, params);
			log.info("-get_access_token-->" + access_token_json);
		} catch (IOException e) {
			return null;
		}
		JSONObject jsonObject = JSON.parseObject(access_token_json);
		return jsonObject.getString("openid");
	}

	@Override
//	@RedisPut(db = 2, key = "CAT_WECHAT_SESSIONKEY_+#code", timeOut = 5, timeUnit = TimeUnit.MINUTES)
	public WxSessionInfo getWxSessionKey(String code) {
		/* 根据code获取session_key */
		String jsonData;
		String url = "https://api.weixin.qq.com/sns/jscode2session";
		Map<String, String> params = new HashMap<String, String>();
		params.put("appid", configs.getWxSmallProgramAppid());
		params.put("secret", configs.getWxSmallProgramSecret());
		params.put("js_code", code);
		params.put("grant_type", "authorization_code");
		try {
			jsonData = WebUtils.doGet(url, params);
			log.info("-get_access_token-->" + jsonData);
		} catch (IOException e) {
			return null;
		}
		// 判断是否请求成功
		if (StringUtils.isEmpty(JSON.parseObject(jsonData).getString("session_key"))) {
			log.error("调用微信失败:" + JSON.parseObject(jsonData).getString("errmsg"));
			return null;
		}
		return JSON.parseObject(jsonData, WxSessionInfo.class);
	}

	@Override
	@RedisPut(rtype = 2, db = 14, key = "CAT_APP_VERSION_INFO", hashKey = "+#ctype+_+#channelid+_+#appId", timeOut = 1, timeUnit = TimeUnit.DAYS)
	public CatAppVersionInfoResp getLastAppVersion(Integer ctype, Integer appId, String channelid) {
		CatAppVersionInfoResp resp = catAppVersionInfoRespDao.selectOne(new CatAppVersion(channelid, ctype, appId),
				"getLastAppVersion");
		return resp;
	}

	@Override
	@RedisPut(db = 6, rtype = 2, key = "CAT_APP_AD_STATUS", hashKey = "+#ctype+_+#cid+_+#vscode", timeOut = 1, timeUnit = TimeUnit.DAYS)
	public Integer getCatAppAdStatus(Integer ctype, String cid, String vscode) {
		// 如果渠道或者版本号为空直接返回
		if (StringUtils.isEmpty(cid) || StringUtils.isEmpty(vscode)) {
			return 1;
		}
		CatAppAd appAd = catAppAdRepository.findByCtypeAndCidAndVscode(ctype, cid, Long.parseLong(vscode));
		return appAd == null ? 1 : appAd.getAstatus();
	}

	@Override
	@RedisPut(rtype = 2, db = 13, key = "CAT_DEV_REGISTER_INFO", hashKey = "+#pid", timeOut = 5, timeUnit = TimeUnit.DAYS)
	public CatDevRegisterInfo getUserRegisterInfo(String pid) {
		// 判断渠道号是否相同
		CatDevRegisterInfo registerInfo = catDevRegisterInfoRepository.findByPid(pid);
		return registerInfo;
	}

	@Override
	public CatDevSignedHistoryResp get7SignInNumberDays(String pid) {
		CatDevSignedHistoryResp historyResp = signedHistoryRespDao.selectOne(new CatDevSignedHistory(pid),
				"get7SignInNumberDays");
		if (historyResp == null) {
			historyResp = new CatDevSignedHistoryResp();
			historyResp.setEndDate("1970-01-01");
			historyResp.setSigns(0);
		}
		return historyResp;
	}

	@Override
	@RedisPut(rtype = 2, db = 14, key = "CAT_APP_USER_IS_NORMAL", hashKey = "+#ctype+_+#pid+_+#isModify", timeOut = 1, timeUnit = TimeUnit.HOURS)
	public Boolean isNormalCatUser(int ctype, String pid, int isModify) {
		CatAppAdOper appAdOper = catAppAdOperDao.selectOne(new CatAppAdOper(pid), "getUserLastDaysData");
		String clientType = ctype == 0 ? "Android" : ctype == 1 ? "IOS" : "ALL";
		Double rate = (Double) redis14.opsForHash().get(AD_STANDARD_CLICK_RATE_KEY, clientType);
		if (rate == null) {
			// 默认正常点击率10%
			redis14.opsForHash().put(AD_STANDARD_CLICK_RATE_KEY, clientType, 10.00);
			rate = 10.00;
		}
		// 判断用户的点击率是否满足正常比例
		if (appAdOper == null || ((double) appAdOper.getClick() / (double) appAdOper.getAshow() * 100) < rate) {
			// 广告点击率过低标识为异常用户
			if (isModify == 1) {
				/* 异步更新用户为异常用户 */
				asyncService.updateCatDevUtype(pid, -1);
			}
			return false;
		}
		// 查询最近几天的pv数据，判断是否满足条件
		Integer pvNum = intDao.selectOne(new CatAppPV(pid), "getUserLastDaysPageCount");
		if (pvNum != null && pvNum < 4) {
			// 用户进入页面数过少,设置为异常用户
			if (isModify == 1) {
				/* 异步更新用户为异常用户 */
				asyncService.updateCatDevUtype(pid, -1);
			}
			return false;
		}
		return true;
	}

	@Override
	@RedisPut(rtype = 2, db = 15, key = "CAT_USER_INVITE_RELATION", hashKey = "+#pid", timeOut = 1, timeUnit = TimeUnit.HOURS)
	public CatDevRelation getInviteRelationByPid(String pid) {
		CatDevRelation inviteInfo = catDevRelationRepository.findByPid(pid);
		if (inviteInfo == null || inviteInfo.getYpid().equals("1111111111")) {
			return null;
		}
		return inviteInfo;
	}

	@Override
	@RedisPut(db = 1, key = "CAT_APPLE_KEYS", timeOut = 1, timeUnit = TimeUnit.HOURS)
	public String getAppleKeys() {
		String keys = null;
		try {
			keys = WebUtils.doGet("https://appleid.apple.com/auth/keys", null);
		} catch (IOException e) {
			log.error("获取苹果公钥失败-->" + e.getLocalizedMessage());
			keys = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"86D88Kf\",\"use\":\"sig\",\"alg\":\"RS256\",\"n\":\"iGaLqP6y-SJCCBq5Hv6pGDbG_SQ11MNjH7rWHcCFYz4hGwHC4lcSurTlV8u3avoVNM8jXevG1Iu1SY11qInqUvjJur--hghr1b56OPJu6H1iKulSxGjEIyDP6c5BdE1uwprYyr4IO9th8fOwCPygjLFrh44XEGbDIFeImwvBAGOhmMB2AD1n1KviyNsH0bEB7phQtiLk-ILjv1bORSRl8AK677-1T8isGfHKXGZ_ZGtStDe7Lu0Ihp8zoUt59kx2o9uWpROkzF56ypresiIl4WprClRCjz8x6cPZXU2qNWhu71TQvUFwvIvbkE1oYaJMb0jcOTmBRZA2QuYw-zHLwQ\",\"e\":\"AQAB\"},{\"kty\":\"RSA\",\"kid\":\"eXaunmL\",\"use\":\"sig\",\"alg\":\"RS256\",\"n\":\"4dGQ7bQK8LgILOdLsYzfZjkEAoQeVC_aqyc8GC6RX7dq_KvRAQAWPvkam8VQv4GK5T4ogklEKEvj5ISBamdDNq1n52TpxQwI2EqxSk7I9fKPKhRt4F8-2yETlYvye-2s6NeWJim0KBtOVrk0gWvEDgd6WOqJl_yt5WBISvILNyVg1qAAM8JeX6dRPosahRVDjA52G2X-Tip84wqwyRpUlq2ybzcLh3zyhCitBOebiRWDQfG26EH9lTlJhll-p_Dg8vAXxJLIJ4SNLcqgFeZe4OfHLgdzMvxXZJnPp_VgmkcpUdRotazKZumj6dBPcXI_XID4Z4Z3OM1KrZPJNdUhxw\",\"e\":\"AQAB\"}]}";
		}
		log.info("-getAppleKeys-->" + JSON.toJSONString(keys, true));
		return keys;
	}

	@Override
	@RedisPut(rtype = 2, db = 13, key = "CAT_DEV_INFO", hashKey = "+#userid", timeOut = 1, timeUnit = TimeUnit.DAYS)
	public String getCatDevUserInfoByUserid(String userid) {
		if (userid == null || userid.length() < 20) {
			return null;
		}
		List<CatDevUserInfo> cacheEntity = catDevUserInfoRepository.findByUserid(userid);
		if (cacheEntity == null || cacheEntity.isEmpty()) {
			return null;
		}
		return JSON.toJSONString(cacheEntity.get(0));
	}

	@Override
	@RedisPut(db = 11, key = "CAT_USER_DEQ_ORDER_NUMBER_+#pid", timeOut = 10, timeUnit = TimeUnit.DAYS)
	public Integer getUserDaEOrderNumber(String pid) {
		int count = goodsSubsidyHistoryRepository.countByPidAndFtypeAndBstatusIn(pid, 3, 1, 2);
		return count == 0 ? null : count;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_SUPERCOUPON_GOODS_LIST_+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public ResultPage<TKSelectionResp> getSupercouponGoodsList(String key, String cid, Pages pages) {
		TBAPI tbapi = TBAPI.getInstance(TBAPI.DEFAULT_TYPE);
		ResultPage<TKSelectionResp> resp = tbapi.getTbkUatmFavoritesItem(Long.parseLong(cid), pages);
		return filterGoods(resp);
	}

	@Override
	@RedisPut(db = 11,rtype = 2, key = "CAT_GOODS_CATEGORY_LIST_TEST" ,hashKey = "+#vscode+_+#rtype", timeOut = 30, timeUnit = TimeUnit.MINUTES)
	public List<CatGoodsCategoryResp> getCategoryList(int rtype,int vscode) {
		List<CatGoodsCategoryInfo> parentList = null;
		List<CatGoodsCategoryInfo> childenList = null;
		//九趣猫1.1.6版本更新，增加拼多多类目信息，其他版本不包含【2020-06-19】
		if((rtype==0 && vscode>=116) || (rtype==1 && vscode>=113)) {
			parentList = catGoodsCategoryRepository.findByLevel(1);
			 childenList = catGoodsCategoryRepository.findByLevel(2);	
		}else {
			parentList = catGoodsCategoryRepository.findByLevelWithOutPDD(1);
			 childenList = catGoodsCategoryRepository.findByLevelWithOutPDD(2);
		}
		  
		Map<Integer, CatGoodsCategoryResp> map = parentList.stream()
				.collect(Collectors.toMap(CatGoodsCategoryInfo::getId, obj -> {
					CatGoodsCategoryResp resp = new CatGoodsCategoryResp();
					BeanUtils.copyProperties(obj, resp);
					return resp;
				}));
		CatGoodsCategoryResp parentCategoryResp;
		for (CatGoodsCategoryInfo category : childenList) {
			CatGoodsCategoryResp resp = new CatGoodsCategoryResp();
			BeanUtils.copyProperties(category, resp);
			parentCategoryResp = map.get(category.getParentId());
			if (parentCategoryResp.getChildrenList() == null) {
				parentCategoryResp.setChildrenList(new ArrayList<>());
			}
			parentCategoryResp.getChildrenList().add(resp);
		}
		List<CatGoodsCategoryResp> collect = map.values().stream().sorted(new Comparator<CatGoodsCategoryResp>() {

			@Override
			public int compare(CatGoodsCategoryResp o1, CatGoodsCategoryResp o2) {
				return o1.getSort() - o2.getSort();
			}
		}).collect(Collectors.toList());
		return collect;
	}

	@Override
//	@RedisPut(db = 11, key = "CAT_USER_NOT_PROMOTED_ORDER_NUM_+#pid", timeOut = 10, timeUnit = TimeUnit.DAYS)
	public int getNotPromotedOrderCount(String pid) {
		int count = intDao.selectOne(CatDevOrderResp.builder().pid(pid).build(), "getNotpromoteOrderCount");
		return count;
	}

	@Override
	@RedisPut(db = 11, key = "CAT_GOODS_MESSSAGE_LIST", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public List<CatAppGoodsMsgResp> getAppGoodsMesssageList(Integer rtype) {
		TBAPI tbapi = TBAPI.getInstance(TBAPI.DEFAULT_TYPE);
		int nowHour = LocalDateTime.now().getHour();
		int size = nowHour - 8 + 1;
		if (size <= 0) {
			return null;
		}
		List<Map<String, String>> favoritesList = getFavoritesList(8);
		String fid;
		if (favoritesList != null && favoritesList.size() > 0) {
			fid = favoritesList.get(0).get("cid");
		} else {
			fid = "2015611021";
		}
		Pages pages = new Pages(1, size);
		ResultPage<TKSelectionResp> resp = tbapi.getTbkUatmFavoritesItem(Long.parseLong(fid), pages);
		ResultPage<TKSelectionResp> resultPage = filterGoods(resp);
		if (resultPage == null) {
			return null;
		}
		int startTime = 8;
		// 转换成商品消息推送类
		List<CatAppGoodsMsgResp> list = JSON.parseArray(JSON.toJSONString(resultPage.getList()),
				CatAppGoodsMsgResp.class);
		for (int i = 0; i < list.size(); i++) {
			CatAppGoodsMsgResp obj = list.get(i);
			obj.setId(obj.getNumIid());
			obj.setPushTime(LocalDate.now().toString() + " "
					+ ((startTime + i) >= 10 ? (startTime + i) : "0" + ((startTime + i))) + ":00:00");
		}
		Collections.reverse(list);
		return list;
	}

	@Override
//	@RedisPut(rtype = 2, db = 13, key = "CAT_DEV_SIGN_IN_STATUS_INFO+#date", hashKey = "+#pid", timeOut = 1, timeUnit = TimeUnit.DAYS)
	public CatDevSignedBeansHistory getTodaySignInStatus(String pid, String date) {
		return signedBeansHistoryRepository.selectLastHistory(pid);
	}

	@Override
	@RedisPut(rtype = 2, db = 11, key = "CAT_TLJ_GOODS", hashKey = "+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public ResultPage<TKTLJGoodsResp> getTljGoodsList(String key, Pages pages) {
		return gdao.listAndPages(new TKTLJGoodsResp(), pages);
	}

	@Override
//  	@RedisPut( db = 11, key = "CAT_TLJ_REMIT_LIST" , timeOut = 10, timeUnit = TimeUnit.SECONDS)
	public List<InviteRemit> getCatDev5088InviteRemitinfo() {
		List<InviteRemit> remitInfo = new ArrayList<InviteRemit>();
		InviteRemit remit1 = new InviteRemit(1, 500, 1);
		InviteRemit remit2 = new InviteRemit(0, 1000, 10);
		InviteRemit remit3 = new InviteRemit(0, 2000, 10);
		InviteRemit remit4 = new InviteRemit(0, 5000, 10);
		InviteRemit remit5 = new InviteRemit(0, 10000, 10);
		remitInfo.add(remit1);
		remitInfo.add(remit2);
		remitInfo.add(remit3);
		remitInfo.add(remit4);
		remitInfo.add(remit5);

		List<InviteRemit> userRemitInfos = rdao.list(new CatDev5088InviteInfoResp(), "remitCountInfo");
		if (userRemitInfos != null && !userRemitInfos.isEmpty()) {
			for (InviteRemit userRemitInfo : userRemitInfos) {
				for (InviteRemit inviteRemit : remitInfo) {
					if (inviteRemit.getIncome() == userRemitInfo.getIncome()) {
						int lcount = inviteRemit.getLcount() - userRemitInfo.getLcount();
						if (lcount < 0) {
							lcount = 0;
						}
						inviteRemit.setLcount(lcount);
						break;
					}
				}
			}
		}
		return remitInfo;
	}


	@Override
	@RedisPut( db = 14, key = "CAT_EVENT_ELEMENT_LIST" , timeOut = 10, timeUnit = TimeUnit.SECONDS)
	public List<CatEventElement> getEventElementList() {
		return catEventElementRepository.findAll();
	}


	@Override
	@RedisPut(db = 11, key = "CAT_REMIT_NUMBER_+#pid", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public Integer getRemitCount(String pid) {
		int count = catDevRemitInfoRepository.countByPidAndRtypeInAndTstatusNot(pid, Arrays.asList(4), -1);
		return count;
	}
	
	@Override
	@RedisPut(db = 11, key = "CAT_HDK_GOODS_CATS", timeOut = 3, timeUnit = TimeUnit.HOURS)
	public List<HdkSuperCategory> getHDKSuperCategory() {
		HdkAPI api = HdkAPI.getInstance();
		return api.getSuperClassify();
	}


	@Override
	@RedisPut(db = 11, key = "CAT_HDK_GOODS_+#key", timeOut = 6000, timeUnit = TimeUnit.SECONDS)
	public ResultPage<HdkGoodsItem> getHdkKeywordItems(String key, String keyword, Integer cid, Integer sort,
			Integer pageNum, Integer pageSize) {
		HdkAPI api = HdkAPI.getInstance();
		return api.getKeywordItems(keyword, sort, pageNum, pageSize, cid);
	}


	@Override
//	@RedisPut(db = 7, rtype = 2, key = "CAT_DAILY_DRAW_LIST", hashKey = "+#pid", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public List<Prize> dailyDrawPrizeList(String pid) {
		return dailyDrawDao.list(new CatDailyDrawDetailResp(pid), "getDailyDrawPrizeList");
	}
	
	@Override
//	@RedisPut(db = 7, rtype = 2, key = "CAT_DAILY_DRAW_RECORD_LIST", hashKey = "+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public ResultPage<Prize> getDailyDrawList(String key, String pid,Integer type, Integer drawStatus,Integer pageNum, Integer pageSize) {
		CatDailyDrawDetailResp detailResp = CatDailyDrawDetailResp.builder().pid(pid).drawStatus(drawStatus).type(type).build();
		return dailyDrawDao.listAndPages(detailResp, "getDailyDrawRecordList", new Pages(pageNum, pageSize));
	}
	
	@Override
	public CatDailyDrawDetailResp getDailyDrawDetail(String key, String pid, Integer drawId) {
		return dailyDrawDetailRespDao.selectOne(new CatDailyDrawDetailResp(drawId,pid), "getDailyDrawDetail");
	}


	@Override
	@RedisPut(db = 11, key = "CAT_HDK_TALENT_INFO_+#talentcat", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public CatTalentInfoResp getTalentInfo(Integer talentcat) {
		// TODO Auto-generated method stub
		HdkAPI api = HdkAPI.getInstance();
		return api.getTalentInfo(talentcat);
	}
	
	@Override
	@RedisPut(db = 11, key = "CAT_HDK_ITEM_LIST_+#key", timeOut = 6000, timeUnit = TimeUnit.SECONDS)
	public ResultPage<HdkGoodsItem> getHdkItemList(String key, Integer nav,  Integer cid, Integer sort,
			Integer pageNum, Integer pageSize) {
		HdkAPI api = HdkAPI.getInstance();
		return api.getItemlist(nav, sort, pageNum, pageSize, cid);
	}

	@Override
	@RedisPut(db = 11, key = "CAT_DOUYIN_LIST_+#key", timeOut = 6000, timeUnit = TimeUnit.SECONDS)
	public List<CatDouYinVideoResp> getHdkDuoyinItems(String key, String itemId, Integer min_id) {
		// TODO Auto-generated method stub
		HdkAPI api = HdkAPI.getInstance();
		return api.getDouyinItems(itemId, min_id);
	}


	@Override
	@RedisPut(db = 11, key = "CAT_NEW_LIST_+#key", timeOut = 5, timeUnit = TimeUnit.HOURS)
	public List<NewItemResp> getNewData(String key, String channel, Integer pageNum, Integer pageSize) {
		// TODO Auto-generated method stub
		JISUAPI instance = JISUAPI.getInstance();
		return instance.getNew(channel, pageSize, pageNum);
	}

	@Override
	@RedisPut(db = 11,rtype = 2, key = "CAT_HDK_GOODS_RANK",hashKey = "+#key", timeOut = 1, timeUnit = TimeUnit.HOURS)
	public List<HdkGoodsItem> hdkRankList(String key, Integer stype, Integer back, Integer min_id, Integer cid,
			Integer item_type) {
		List<HdkGoodsItem> result=HdkAPI.getInstance().getGoodsRank(stype, cid, min_id, back, item_type);
		return result;
	}

	/**
	 * 获取今日推荐商品信息
	 * @param sid
	 * @param key
	 * @param pageNum
	 * @param pageSize
	 * @param sorttype
	 * @param b
	 * @return
	 */
	@Override
	public PddDdkGoodsSearchResponse getPddShopTj(Long sid, String key, int pageNum, int pageSize, Integer sorttype,
			boolean withCoupon) {
		// TODO Auto-generated method stub
		PddDdkGoodsSearchResponse shopList = PDDAPI.getInstance(1,1).getTjshops(sid,pageNum, pageSize, sorttype, withCoupon);
		return shopList;
	}

	/**
	 * 获取每日推荐商品
	 */
	@Override
	//@RedisPut(db = 10, rtype = 2, key = "CAT_JD_GOODS_LIST", hashKey = "+#key", timeOut = 10, timeUnit = TimeUnit.MINUTES)
	public UnionOpenGoodsQueryResponse getJdTjGoods(int ctype, String key, int pageIndex, int stype, String sort,
		int isCoupon) {
		//排序字段(price：单价, commissionShare：佣金比例, commission：佣金， inOrderCount30Days：30天引单量， inOrderComm30Days：30天支出佣金)
		String sortName="price";
		if(stype==0) {
		sortName="price";
		}else if(stype==1) {
		sortName="commissionShare";
		}else if(stype==2) {
		sortName="commission";
		}else if(stype==3) {
		sortName="inOrderCount30Days";
		}else if(stype==4) {
		sortName="inOrderComm30Days";
} 
	UnionOpenGoodsQueryResponse result=JDAPI.getInstance(ctype).getTjGoods(pageIndex, "",sortName,sort, isCoupon,"");
	if(result!=null&&result.getData()!=null&&result.getData().length>0) {
		return result;
	}
		return null;
	}
}
